Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mozilla's bind function question

Tags:

Had a question about a implementation of bind function that I found on Mozilla's site. For the most part it makes sense to me, but I cant figure out what this check is for...

this instanceof nop ? this : ( obj || {} )  

in the bind function. Obviously its checking if 'this' is the empty function, but why would you need to bind the empty function. I have tried it in firebug, it works, but what is the point? Just trying to increase my javascript knowledge so any help would be appreciated.

if ( !Function.prototype.bind ) {    Function.prototype.bind = function( obj ) {      var slice = [].slice,     args = slice.call(arguments, 1),      self = this,      nop = function () {},      bound = function () {       return self.apply( this instanceof nop ? this : ( obj || {} ),                            args.concat( slice.call(arguments) ) );         };      nop.prototype = self.prototype;      bound.prototype = new nop();      return bound;   }; } 
like image 504
mike Avatar asked Apr 25 '11 00:04

mike


People also ask

What does the function bind () do?

Summary. The bind() method creates a new function, when invoked, has the this sets to a provided value. The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

How do you call a function in bind?

You can use call() / apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.

When would you use the bind function?

The bind method creates a new function from another function with one or more arguments bound to specific values, including the implicit this argument.

How do you bind a function in TypeScript?

In JS, the first argument (within the bind() call) bind 'this' to the given object. But in TypeScript, functions created from function. bind are always preserve 'this'.


1 Answers

Its allows you to call the bound function as a constructor without being bound to the original object. In other words the "bound" function will still work just like the original, unbound version if you call it with new.

Here's an example:

var obj = {};  function foo(x) {     this.answer = x; } var bar = foo.bind(obj);   // "always" use obj for "this"  bar(42); console.log(obj.answer);   // 42  var other = new bar(1);    // Call bar as a constructor console.log(obj.answer);   // Still 42 console.log(other.answer); // 1 

How it works

To simplify the explanation, here's a simplified version of the code that only binds this and doesn't handle arguments or a missing obj parameter:

Function.prototype.bind = function( obj ) {   var self = this,   nop = function () {},   bound = function () {     return self.apply( this instanceof nop ? this : obj, arguments );   };    nop.prototype = self.prototype;   bound.prototype = new nop();    return bound; }; 

The function that gets returned by Function.prototype.bind behaves differently depending on whether you use it as a function, or a constructor (see Section 15.3.4.5.1 and 15.3.4.5.2 of the ECMAScript 5 Language Specification). The primary difference, is that it ignores the "bound this" parameter when it's called as a constructor (since inside a constructor, this needs to be the newly-created object). So the bound function needs a way to determine how it's being called. For example, bound(123) vs. new bound(123) and set this accordingly.

That's where the nop function comes in. It's essentially acting as an intermediate "class" so that bound extends nop which extends self (which is the function bind() was called on). That part is set up here:

nop.prototype = self.prototype; bound.prototype = new nop(); 

When you call the bound function, it returns this expression:

self.apply( this instanceof nop ? this : obj, arguments ) ) 

this instanceof nop works by following the prototype chain to determine the if any prototype of this is equal to nop.prototype. By setting nop.prototype = self.prototype and bound.prototype = new nop(), any object created with new bound() will be created with the original prototype from self via bound.prototype. So inside the function call, this instanceof nop (i.e. Object.getPrototypeOf(nop) == nop.prototype) is true and self gets called with this (the newly created object).

In a normal function call, 'bound()' (without new), this instanceof nop would be false, so obj gets passed as the this context, which is what you would expect on a bound function.

The reason for using the intermediate function is to avoid calling the original function (in the line bound.prototype = new nop();), which may have side effects.

like image 96
Matthew Crumley Avatar answered Sep 17 '22 18:09

Matthew Crumley