使用this.function的Javascript导致'无方法'错误

时间:2014-03-15 21:29:14

标签: javascript

我有这个简单的Javascript对象,它在一个本地方法中调用自己的原型方法。 [看我的编辑]

var Obj = function() {
    function inner() {
        this.exported();
    }

    this.exported = function() {
        alert("yay!");
    };
};

var test = new Obj();
Obj.exported();

但是,我收到错误TypeError: Object function() {...} has no method 'exported'。 知道应该怎么做吗?

编辑: 哎呀,刚才意识到我从来没有打过内心(),但感谢帕特里克回答这个部分。这是一个更好的例子

var Obj = function() {

    this.exported = function() {
        inner();
    };

    function inner() {
        this.yay();
    }

    this.yay = function() {
        alert("yay!");
    };
};

var test = new Obj();
test.exported();

我得到TypeError: Object [object global] has no method 'exported'

2 个答案:

答案 0 :(得分:3)

应该使用

test.exported();

而不是

Obj.exported();

您应该在exported()对象上调用test方法,而不是在Obj构造函数上调用。

<强>更新

到达function inner(){...}内部后。 this是指全局window而非Obj,因此从this传递实际对象inner(this)并从该传递的对象调用export() function inner(cthis){...},类似于。

function inner(cthis) {
    //----------^--get Obj on here
    cthis.exported();
}

this.exported2 = function() {
    inner(this);
   //------^--pass Obj from here
};

DEMO

答案 1 :(得分:2)

要调用导出,您需要将其分配给您指定实例的变量:

test.exported();

同样对于inner函数,您无法使用this来访问Obj对象,因为它引用window。 保存对this的引用,然后使用它来调用函数

var Obj = function() {
    var _this = this;
    function inner() {
        _this.exported();
    }

    this.exported = function() {
        alert("yay!");
    };
};