"this & object prototypes": ch2 issue about polyfill of Function.prototype.bind()
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.
any help?
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.
update polyfill for second edition.
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