0

以下是 JavaScript 中两个广为人知的代码片段:

Function.prototype.method = function (name, func) {
        this.prototype[name] = func;
        return this;
};

Number.method('integer', function () {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
});

显然,this第二个片段中的 代表调用增强integer方法的 Number 对象。this第一个片段中的那个怎么样?从这个prototype属性我们可以猜到它代表正在被扩充的构造函数,但片段背后的逻辑对我来说是难以捉摸的。谁能详细解释一下?谢谢。

4

3 回答 3

2

Function is the global object which all functions use, just like how Number is the global object for Numbers. They can be used as constructors but also apply to literals, i.e. new Function(); and function () {} both relate to Function.

The prototype Object of a constructor is the place where you define properties and methods for all instances made by that constructor. Constructors are functions and in JavaScript, functions are objects.

A method is just another name for a function, usually describing one which is a property of an object.

Setting a method on Function.prototype hence means every function inherits that method.

Therefore, the this in the method bar on prototype of constructor Foo (Foo.prototype.bar) is equal to one of

  • Foo.prototype if invoked as Foo.prototype.bar()
  • An instance of Foo if invoked from that instance, e.g. z in var z = new Foo(); z.bar();
  • Whatever you've defined this to be using call, apply or bind
  • The global object if invoked without context, i.e. var b = Foo.prototype.bar; b();

In your code, this is expected to be the second of the above, because Number is a function because it is a constructor, and hence an instance of Function.

于 2013-09-26T02:24:14.080 回答
0

作为方法调用的任何函数中的this值始终是调用该方法的对象。所以在 中Number.method(),它将是Number构造函数。

当您在任何其他对象上调用方法时,它的行为方式完全相同,例如:

var obj = {
    someMethod : function() { 
        console.log(this);
    }
}
obj.someMethod(); // logs obj

上面的例子和你的唯一区别是,这里的方法是在对象本身上找到的,而在你的例子中,它是通过查找原型链找到的。

于 2013-09-26T01:55:15.890 回答
0

method方法中,this将是对Function调用该方法的对象的引用。在示例中,它将是对该Number函数的引用。

作为Number一个可以使用new关键字创建的内置类,它实际上是一个函数,这就是Function原型适用于它的原因。

于 2013-09-26T01:45:53.770 回答