【问题标题】:Why is a function wrap unside a function object not called in javascript [duplicate]为什么在javascript中未调用函数对象中的函数包装[重复]
【发布时间】:2016-02-08 21:41:46
【问题描述】:

我有 JavaScript 函数作为对象:

function hexMesh(){
     var side=25;
     console.log('hexMesh');

     function drawOver(){
     }
}  

如您所见,它有一个函数调用drawOver

我尝试使用如下构造函数来调用它:

window.onload = function() {
    hexMeshObj=new hexMesh();
    hexMeshObj.drawOver();
}

但它给了我错误说undefined is not a function

现在我知道我可以在对象的原型中声明该函数,但我不想这样做。

这里是JSFiddle

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你不能那样使用 JavaScript!

    解决方案:使用类类原型(请不要将它们视为类,尽管它们提供了继承)

    var x = function(v){ this.test = v; } // This is your constructor
    x.prototype.show = function(){ console.log("TEST", this.test); } // This is a prototype with this as a context
    
    var y = new x(true);
    y.show(); // Logs TEST true
    

    编辑: 或者(虽然原型方式更好,因为它提供了真正的inheritance the oop way

    var x = function(v){
    var context = this;
    this.test = v;
    this.show = function(){
        console.log('test', context.test)
    });
    

    如果需要,另一种方法是使用bind 绑定上下文。

    【讨论】:

    • 包含一些关于为什么使用原型比第二种方式更好的信息可能会有所帮助。
    • 添加了参考。感谢您的建议。
    • 我正在寻找另一种方法,我知道我可以使用原型来做到这一点,但我不希望该函数位于对象的原型中,因为它在我的情况下没有意义, 谢谢
    • 我添加了有关绑定的信息。您可以使用 bind(this) 实现相同的上下文(这就是它的范围)。第二点,这个问题不是重复的,因为它没有严格按照设置引用问题的方式要求 oop。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2022-01-21
    • 1970-01-01
    • 2016-10-10
    • 2012-09-21
    • 2018-04-27
    • 1970-01-01
    相关资源
    最近更新 更多