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有什么区别?
因为:
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)
this
指的是Function.prototype
因为你打电话.method
给那个.所以,你正在使用Function.prototype.prototype
哪个不存在.
使用Function.method(...)
或this[name] = ...
消除其中一个.prototype
.