gpt4 book ai didi

javascript - 为什么 Function.prototype.bind 返回构造函数?

转载 作者:行者123 更新时间:2023-11-28 00:46:16 24 4
gpt4 key购买 nike

我正在查看Function.prototype.bind方法的polyfill。

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 && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};

fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();

return fBound;
};
}

有人可以解释一下我为什么要这样做吗?如果我不使用 new 运算符调用我的 fn ,我认为此步骤是不必要的。如果不通过 new 运算符调用,为什么返回的 fn 需要是一个构造函数?。

fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;

我们可以做下面这样的事情,而不是创建一个新的构造函数吗?

fBound.prototype = Object.create(this.prototype);
return fBound

最佳答案

你可以...如果支持Object.create

但是如果您要对Function.prototype.bind进行polyfill,那么您可能也必须对Object.create进行polyfill。

Object.create的polyfill基本上是你觉得不必要的部分:

Object.create = (function() {
var fNOP = function() {};
return function (prototype) {
if (arguments.length > 1) throw Error('Second argument not supported');
if (typeof prototype != 'object') throw TypeError('Argument must be an object');
fNOP.prototype = prototype;
var result = new fNOP();
fNOP.prototype = null;
return result;
};
})();

关于javascript - 为什么 Function.prototype.bind 返回构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346124/

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