Javascript:原型方法错误?

时间:2010-02-05 14:44:21

标签: javascript function-prototypes use-strict

我在这段代码中得到“TestFunc is not defined”错误......

/* 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"

2 个答案:

答案 0 :(得分:3)

// 1.
this.TestFunc ();

没关系。这将有效,其他电话被删除。

(好吧,只要你不从它的所有者那里剥离RealFunc并自己调用它,如var method= myObj.RealFunc; method();或通过事件处理程序或超时,它就可以工作。在这种情况下RealFunc中的this不是MyObject实例,您需要查看闭包或Function.bind才能使它工作。)

// 2.
TestFunc ();

不,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 :(得分:1)

变体1似乎是正确的。我在ExecuteJS中尝试了你的代码并跳过了2.和3.它有效(虽然我删除了对console.log的调用并将其更改为alert)。在TestFunc内调用RealFunc

如果删除"use strict";会怎样?