Function.prototype.bind = function() {
var $this = arguments[0];
return this.apply($this, Array.prototype.slice.call(arguments, 1));
};
在实际应用中是否足够好?
最佳答案
没有。这段代码有一些我不喜欢的地方,以及它不起作用的一些原因。
首先,大多数人不会以这种方式分配参数。它占用额外的空间而没有额外的效果。如果变量名称应根据参数数量/参数类型更改,则仅使用 arguments 变量。要分配 $this
你应该这样做..
Function.prototype.bind = function($this) {
其次,bind 应该返回一个函数。您的返回任何 this
返回的内容。您的函数更像是 Function:call
,然后是 Function:bind
。
要修复它,您需要做的是让它返回一个函数,该函数在运行时将返回函数返回的任何内容。
试试这个:
Function.prototype.bind = function($this) {
// `this` changes inside the function, so we have to give it a safe name.
var self = this;
return function () {
return self.apply($this, Array.prototype.slice.call(arguments, 1));
}
};
此外,更多现代浏览器内置了此函数的 ECMAScript 5 标准。该函数是用纯 JavaScript 编写的,因此对于较旧的浏览器,只需包含此 code suggested by Mozilla :
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ), args.concat( slice.call(arguments) ) );
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
关于javascript - 这是一个好的绑定(bind)方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6142528/