TypeError:调用Function.prototype.method()时未定义this.prototype [英] TypeError: this.prototype is undefined when calling Function.prototype.method()
问题描述
现在我正在阅读有关增强类型的章节:
Function.prototype.method = function(name,func){
this.prototype [name] = func;
返回此;
};
更新:
为什么下面的代码没有工作?
js> Function.prototype.method(test,function(){print(TEST)});
typein:2:TypeError:this.prototype未定义
但下面的代码没有问题:
js> Function.method(test,function(){print(TEST)});
函数Function(){[native code]}
为什么这段代码有效?
js> var obj = {status:ST};
js> typeof obj;
对象
js> obj.method = function(){print(this.status)};
(function(){print(this.status);})
js> obj.method();
ST
obj是object。
但是我可以调用方法方法就可以了。
Function.prototype.method和obj.method有什么区别?
.method ,所以引用 Function.prototype
code>就此。因此,您正在使用不存在的 Function.prototype.prototype
。
使用 Function.method(...)
或 this [name] = ...
来消除 .prototype
s。
I am reading the book "Javascript: The good parts".
Now I am reading chapter about Augmenting Types:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
UPDATE:
Why following code does not work?
js> Function.prototype.method("test", function(){print("TEST")});
typein:2: TypeError: this.prototype is undefined
But following code works without problems:
js> Function.method("test", function(){print("TEST")});
function Function() {[native code]}
Why this code works?
js> var obj = {"status" : "ST"};
js> typeof obj;
"object"
js> obj.method = function(){print(this.status)};
(function () {print(this.status);})
js> obj.method();
ST
"obj" is object.
But I can call method "method" on it.
What is the difference between Function.prototype.method and obj.method?
解决方案 this
refers to Function.prototype
because you called .method
on that. So, you're using Function.prototype.prototype
which does not exist.
Either use Function.method(...)
or this[name] = ...
to eliminate one of the .prototype
s.
这篇关于TypeError:调用Function.prototype.method()时未定义this.prototype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!