如何解决不带.apply的Javascript函数别名
| 我读了此书,并理解了它,但是,有没有一种方法可以附加一个函数,以始终在特定范围内执行函数别名,而无需使用函数别名的用户必须使用笨拙的.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;
};
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。