问题描述
|
Function.prototype.bind = function() {
var $this = arguments[0];
return this.apply($this,Array.prototype.slice.call(arguments,1));
};
在实际应用中使用是否足够好?
解决方法
否。对于此代码,我有些不满意的地方,并且有一些原因使其无法正常工作。
首先,大多数人不会以这种方式分配参数。它占用了额外的空间,没有任何额外的效果。仅当变量名称根据参数数量/参数类型而变化时,才使用arguments变量。要分配“ 1”,您应该做..
Function.prototype.bind = function($this) {
其次,绑定应返回一个函数。 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编写,因此对于较旧的浏览器,只需包含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;
};
}