为什么函数包装不隐藏javascript中未调用的函数对象

Why is a function wrap unside a function object not called in javascript

本文关键字:函数 调用 对象 javascript 包装 隐藏 为什么      更新时间:2023-09-26

我有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!

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

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

编辑:或者(尽管原型方式更好,因为它提供了真正的继承oop方式)

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

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