Thursday 15 March 2012

JavaScript function/method context check -


I know how to use methods to change the function / method call references: Apply, Bind, Call My question is, is there a way to check that the function / method has already set its reference?

  // given beta beta; Function alpha () {return; } Check for reference binding on functionContextSet (fn) {/ * fn * /} beta = alpha.bind ("hello"); IsContextSet (alpha); // Return is false CODEXSAT (beta); // Return correct   

I think I already know the answer but thought that I would ask anyway, if not for any other reason: 1. Confirm my belief , Or 2. Learn something I'm sure that I am not the first to ask this question, but I have not really received any answers, because I know how to use it: .apply (), .call (), Or bound ().

no

Basically, as "changing" of the binding reference, it changes a function in one that calls first with a particular reference.

Functions can be bound in many ways, for example, I can tie it myself:

  function bind (FN, CTX) {return function () {fn .apply (ctxt, arguments); }; }   

Or, I could tie it with the function. Prototype Bind, or a shim, which does the same thing, or _bind of underscore. I could bind it with additional initial arguments of reference, in each case, there is no way to tell that what actually happened without executing the function.

Binding is one of several ways to convert one function to another. I can change the function or execute twice to execute one second from now on. There is nothing magic about binding; This creates a new function based on the old one, there is no special clock called [[bound_to]] set on the function, which you can check (unless you use your own custom implementation of the bind, As another answer suggests).

The closest I can imagine coming out is probably checking the bound function against an unbound version and see if it is equal.

  function log_this () {console.log (this);} var bound_func = log_this.bind (my_var); Console.log (log_this === bound_func); // FALSE    

No comments:

Post a Comment