You-Dont-Know-JS icon indicating copy to clipboard operation
You-Dont-Know-JS copied to clipboard

"this & object prototypes": ch2 issue about polyfill of Function.prototype.bind()

Open zxfwinder opened this issue 10 years ago • 4 comments

The snippet in the polyfill of Function.prototype.bind() :

this instanceof fNOP && oThis 
? this : oThis

I cannot really understand why still need && oThis even though this instanceof fNOP already indicate that the function invoked with new operater.

I try this polyfill with below snippet

function foo(p1,p2) {
        this.val = p1 + p2;
}
var bar = foo.bind( null, "p1" );
var baz = new bar( "p2" );
baz.val; // p1p2

but the result is undefined :( The correct result can appear once I comment && oThis.

zxfwinder avatar Jun 18 '15 03:06 zxfwinder

any help?

zxfwinder avatar Jul 03 '15 00:07 zxfwinder

TBH, I'm not sure I know why it was there or not. Just spent a few minutes checking the spec and I'm not really clear on how the check should happen. But:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind$compare?locale=en-US&to=763553&from=747163

Someone removed it from the polyfill. So maybe it wasn't supposed to be there. Shrugs. I kinda doubt it matters, fwiw.

getify avatar Jul 03 '15 01:07 getify

update polyfill for second edition.

getify avatar Sep 03 '15 03:09 getify

The problem of using the polyfill still occurs with the latest code on Github.

function foo(p1,p2) {
        this.val = p1 + p2;
}
var bar = foo.bind( null, "p1" );
var baz = new bar( "p2" );
baz.val; // p1p2

The value of baz.val is also undefined, as is mentioned by @zxfwinder

I think the problem lies in how the polyfill is used in the book. This problem only happens when foo is bound with null.

var bar = foo.bind( null, "p1" );

This way, this is ignored, and the default binding rule is triggered. global.val is p1p2

If foo is bound with an empty object, it works as expected. Here is my revision:

function foo(p1,p2) {
        this.val = p1 + p2;
}
var dummyObj= {}
var bar = foo.bind( dummyObj, "p1" );
var baz = new bar( "p2" );
dummyObj.val //unfined
baz.val; // p1p2

injune1123 avatar Jun 03 '18 01:06 injune1123