幕布斯1515069
2021-07-12 13:53
稍微修改了代码试了一下,结果也是一样的,请问为什么polyfill写法要fNOP呢?
Function.prototype.myBind = function(_that){ var fn = this; // fn = foo var _arguments = Array.prototype.slice.call(arguments).slice(1) var fNOP = function(){}, fBound = function(){ console.log(this) var that = this instanceof fn && _that ? this : _that; var args = Array.prototype.slice.call(arguments) var bindArgs = _arguments.concat(args) return fn.apply(that, bindArgs) }; fBound.prototype = new fn(); // fBound继承了fNOP的原型,也就是fn的原型,去修正返回的fBound函数的prototype对象 return fBound;}function foo(){ this.b = 100; return this.a}var func = foo.bind({a:1})func()new func()
Function.prototype.myBind = function(_that){ var fn = this; // fn = foo var _arguments = Array.prototype.slice.call(arguments).slice(1) var fBound = function(){ console.log(this) var that = this instanceof fn && _that ? this : _that; var args = Array.prototype.slice.call(arguments) var bindArgs = _arguments.concat(args) return fn.apply(that, bindArgs) }; fBound.prototype = new fn(); // fBound继承了fNOP的原型,也就是fn的原型,去修正返回的fBound函数的prototype对象 return fBound; } function foo(){ this.b = 100; return this.a } var func = foo.bind({a:1}) func() new func()
上面提问的代码格式错乱了,下面这里是正确排版,没有用fNOP也可以得到一样的效果,为什么需要用fNOP函数呢?
JavaScript深入浅出
281111 学习 · 1020 问题
相似问题