学习Javascript绑定方法说明

时间:2013-11-10 21:33:23

标签: javascript

我每天都在使用Ruby,但现在Javascript到处都是,我也需要学习这门语言。

我从“学习JavaScript设计模式”开始,现在我读了第6版“JavaScript:The Definitive Guide”。

我也正在阅读一些博客。

我找到了一段代码片段,我完全不明白:

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;
  };
}

我知道它会检查是否定义了名为bind的函数,如果没有,则定义它。

但为什么要检查Function对象的原型?

为什么不是简单的检查:

if(typeof bind != 'function')

1 个答案:

答案 0 :(得分:2)

因为bind是类型为Function的对象的类方法,而不是Javascript提供的全局函数。