Javascript:原型方法错误?
当这段代码Javascript:原型方法错误?,javascript,function-prototypes,use-strict,Javascript,Function Prototypes,Use Strict,当这段代码 /* 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
/* 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"
那很好。这样就行了,其他电话都被删除了
(好吧,只要你不从它的所有者那里剥离RealFunc
并自己调用它,它就可以工作,比如var method=myObj.RealFunc;method();
或通过事件处理程序或超时。在这种情况下,RealFunc中的this
将不是MyObject实例,您需要查看闭包或函数。bind
使其工作。)
不,TestFunc未定义为局部或全局范围内的变量。这会导致您从Firebug获得错误
// 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
)<在RealFunc
中调用code>TestFunc
如果删除
“use strict”,会发生什么情况代码>?我在firebug中试过,只使用了这个.TestFunc()
和其他两个注释,效果很好。再试一次。ECMAScript第五版的“严格使用”不会起任何作用。。。然而不过,我期待着浏览器在它的位置发布!啊哈!我没有在上面的简化版本中包含它,因为我完全忘记了在eventhandler中“this”会发生什么,但是RealFunc()确实是一个事件处理程序……是的,我也这么怀疑。。。方法绑定和这个在JavaScript中的工作方式与其他编程语言相比非常奇怪;这可能是最常见的骗局。
// 2.
TestFunc ();
// 3. (I didn't really think this would work,
// but thought it was worth a try...)
MyObject.TestFunc ();