问题描述
|
我读了此书,并理解了它,但是,有没有一种方法可以附加一个函数,以始终在特定范围内执行函数别名,而无需使用函数别名的用户必须使用笨拙的.apply东西?
解决方法
您可以使用新的ECMAScript 5
.bind()
方法。不支持浏览器的替代实现(摘自我链接到的MDC文档):
// Function.prototype.bind polyfill
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
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 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) ) );
};
bound.prototype = this.prototype;
return bound;
};
}