You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
}
`
接着,这是《你不知道的JavaScript》中的一段代码,这段代码怎么执行的?
`
function foo(something) {
this.a = something;
}
var obj1 = {};
var bar = foo.bind( obj1 );
bar( 2 );
console.log( obj1.a ); // 2
var baz = new bar(3);
console.log( obj1.a ); // 2
console.log( baz.a ); // 3
`
首先看这一句var bar = foo.bind( obj1 ); , bind被foo调用(bind的执行环境是foo),因此polyfill中fToBind = this,的this就是foo,模拟过程如下:
`
var obj1 = {'__proto__': foo.prototype}
fNOP.apply(obj1, arguments);
fbound.prototype = obj1;
bar = fBound;
先看MDN上bind的polyfill
`
`
接着,这是《你不知道的JavaScript》中的一段代码,这段代码怎么执行的?
`
`
首先看这一句
var bar = foo.bind( obj1 );
, bind被foo调用(bind的执行环境是foo),因此polyfill中fToBind = this,
的this就是foo,模拟过程如下:`
`
然后看这一句
var baz = new bar(3);
,模拟如下:`
`
The text was updated successfully, but these errors were encountered: