gpt4 book ai didi

JavaScript function.prototype.bind polyfill

转载 作者:行者123 更新时间:2023-11-29 23:56:54 25 4
gpt4 key购买 nike

为什么我们需要在这里使用 instanceOf 而在这种情况下结果将为真?

if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable 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)));

//这里为什么要用instanceOf };

    if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();

return fBound;
};
}

//什么情况下结果为真?

最佳答案

我认为这是下面问题的重复,只是变量的命名在 2011 年提出时略有不同,所以很容易没有注意到它:

mozilla's bind function question

查看该问题以获得完整解释(如果您同意这是您问题的答案,请点赞答案),但关键点在于:

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.

关于JavaScript function.prototype.bind polyfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41364976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com