Javascript 使用 this.function 会导致 'has no method' 错误

标签 javascript

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

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'。 知道该怎么做吗?

编辑: 哎呀,刚刚意识到我从未调用过 inside(),但无论如何还是感谢帕特里克回答了这一部分。这是一个更好的例子

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'

最佳答案

应该使用

test.exported();

而不是

Obj.exported();

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

更新

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

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

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

DEMO

关于Javascript 使用 this.function 会导致 'has no method' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22429986/

相关文章:

javascript - 静态与动态 SVG

javascript - 尝试从 JavaScript 转换为 jquery

javascript - React render for 循环运行两次

javascript - setInterval() 中访问 DOM 不正确

javascript - 使用 URL 设置变量

javascript - Carrierwave 图片上传不起作用

javascript - 无法在 React 服务器端渲染中处理 UnhandledPromiseRejectionWarning

javascript - 编写一个函数,返回二进制字符串中连续零的最长序列

javascript - 在 iframe 中预览 pdf 的一部分?

javascript - 具有多种功能的 Lodash 过滤器