TypeError:调用Function.prototype.method()时未定义this.prototype

Vol*_*lyy 5 javascript prototype function

我正在读"Javascript:The good parts"这本书.
现在我正在阅读关于增强类型的章节:

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};
Run Code Online (Sandbox Code Playgroud)

更新:
为什么以下代码不起作用?

js> Function.prototype.method("test", function(){print("TEST")});
typein:2: TypeError: this.prototype is undefined
Run Code Online (Sandbox Code Playgroud)

但是下面的代码没有问题:

js> Function.method("test", function(){print("TEST")});
function Function() {[native code]}
Run Code Online (Sandbox Code Playgroud)

为什么这段代码有效?

js> var obj = {"status" : "ST"};
js> typeof obj;
"object"
js> obj.method = function(){print(this.status)};
(function () {print(this.status);})
js> obj.method();
ST
Run Code Online (Sandbox Code Playgroud)

"obj"是对象.
但我可以在上面调用方法"方法".
Function.prototype.method和obj.method有什么区别?

Rob*_*b W 5

因为:

Function instanceof Function           // <--- is true
Function.prototype instanceof Function // <-- is false
Run Code Online (Sandbox Code Playgroud)
  • Function.prototype 是一个Object,并不从Function构造函数继承任何内容.
  • Function是一个构造函数,也是一个函数,所以它继承了方法Function.prototype.

  • 在调用时Function.method,您正在调用method实例的方法Function.所以,this指向创建的实例Function.
  • 在调用时Function.prototype.method,您正在调用对象的普通方法.this指向Function.prototype.

为了澄清,这是一个例子:

Function.method()                // is equivalent to
(function Function(){}).method()
(new Function).method()          // Because Function is also a function

Function.prototype.method // No instance, just a plain function call
Run Code Online (Sandbox Code Playgroud)


pim*_*vdb 5

this指的是Function.prototype因为你打电话.method给那个.所以,你正在使用Function.prototype.prototype哪个不存在.

使用Function.method(...)this[name] = ...消除其中一个.prototype.