[英]TypeError: this.prototype is undefined when calling Function.prototype.method()
I am reading the book "Javascript: The good parts". 我正在读“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. “obj”是对象。
But I can call method "method" on it. 但我可以在上面调用方法“方法”。
What is the difference between Function.prototype.method and obj.method? Function.prototype.method和obj.method有什么区别?
Because: 因为:
Function instanceof Function // <--- is true
Function.prototype instanceof Function // <-- is false
Function.prototype
is an Object, and does not inherit anything from the Function contructor. Function.prototype
是一个Object,不会从Function构造函数继承任何内容。 Function
is a constructor, but also a function, so it inherits methods from Function.prototype
. Function
是一个构造函数,也是一个函数,因此它继承了Function.prototype
方法。 Function.method
, you're calling the method
method of an instance of Function
. 调用Function.method
,您正在调用Function
实例的method
方法。 So, this
points to the created instance of Function
. 因此, this
指向创建的Function
实例。 Function.prototype.method
, you're invoking an ordinary method of an object. 调用Function.prototype.method
,您正在调用对象的普通方法。 this
points to Function.prototype
. this
指向Function.prototype
。 To clarify, here's an example: 为了澄清,这是一个例子:
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
this
refers to Function.prototype
because you called .method
on that. this
是指Function.prototype
因为你在那上面调用了.method
。 So, you're using Function.prototype.prototype
which does not exist. 所以,你使用的是不存在的Function.prototype.prototype
。
Either use Function.method(...)
or this[name] = ...
to eliminate one of the .prototype
s. 使用Function.method(...)
或this[name] = ...
来消除其中一个.prototype
。
prototype is only used when you are declaring the function, but not when you are calling it. 原型仅在您声明函数时使用,但不在您调用时使用。 Prototype makes the function a member of the object that gets created with every instance of that object. Prototype使该函数成为使用该对象的每个实例创建的对象的成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.