【发布时间】:2011-09-16 14:12:04
【问题描述】:
在Mozilla开发者中心,有一个关于Function.prototype.bind功能的页面,并为不支持该功能的浏览器提供了兼容功能。
但是,在分析此兼容性代码时,我无法找出他们使用instanceof nop 的原因。 nop 已设置为 function() {}。这与bind 上的 ECMA 规范的哪一部分相对应?什么变量是function() {} 的实例?
下面返回false,所以我不完全知道它是干什么用的。进行instanceof function() {} 检查时,哪些情况会返回 true?
(function() {}) instanceof (function() {}) // false
代码如下:
Function.prototype.bind = function( obj ) {
if(typeof this !== '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;
};
【问题讨论】:
标签: javascript function bind instanceof prototype-programming