使用Javascript:原型方法错误?
-
18-09-2019 - |
题
我收到一个“没有定义TestFunc”错误时,该位的代码...
/* my_object.js */
"use strict";
function MyObject (param) {
this.param = param;
}
MyObject.prototype.TestFunc = function () {
console.log ('in TestFunc');
}
MyObject.prototype.RealFunc = function () {
// I have tried 3 different ways to call TestFunc:
// 1.
this.TestFunc ();
// 2.
TestFunc ();
// 3. (I didn't really think this would work,
// but thought it was worth a try...)
MyObject.TestFunc ();
}
...被从该位的代码运行:
/* index.js */
var myObj = new MyObject ('test');
myObj.RealFunc (); // Firebug: "TestFunc is not defined"
解决方案
// 1.
this.TestFunc ();
这很好。这会工作,去除了其他呼叫。
(嗯,只要你不从它的主人剥离RealFunc
并调用它自身,像var method= myObj.RealFunc; method();
或通过事件处理或超时工作。在RealFunc这种情况下,this
不会是为MyObject实例,你需要看看关闭或Function.bind
才能正常工作。)
// 2.
TestFunc ();
不,TestFunc不被定义为本地或全局范围的变量。这将导致你从萤火虫得到错误。
// 3. (I didn't really think this would work,
// but thought it was worth a try...)
MyObject.TestFunc ();
没有,你是对的。 :-)它将被MyObject.prototype.TestFunc.call(this)
,明确地进行。
JavaScript并通过将一些同样的方法对标准的构造函数的那种混淆事内置对象作为他们的原型(例如存在String.split
这里真的只有String.prototype.split
应该)。但是,这不会发生在自己的对象,除非你明确地说,像MyObject.TextFunc= MyObject.prototype.TextFunc
。
其他提示
变体1似乎是正确的。我想你的代码ExecuteJS和跳过2和3,它的工作(虽然我删除调用console.log
,改变它alert
)。 TestFunc
称为RealFunc
内。
如果您删除"use strict";
会发生什么?
不隶属于 StackOverflow