2014-12-30 36 views
0

我有一个JavaScript(Node.js,如果它很重要)应用程序中的以下对象。如何阻止函数被视为javascript对象中的属性?

function myObject (myInput){ 
    this.myValue = myInput; 
    this.myAssociativeArray = {}; 
    this.myAssociativeArrayLen = function() { 
     var k; 
     var l = 0; 
     for (k in this.users){ 
      l = l + 1; 
     } 
     return l; 
    }; 
} 

当我致电长度的功能,并将其登录到控制台我得到这个作为输出:

function() { 
    var k; 
    var l = 0; 
    for (k in this.myAssociativeArray){ 
     l = l + 1; 
    } 
    return l; 
} 

我真的也不肯定这是怎么发生的,但似乎该函数被视为字符串属性,但我没有引号,那么情况怎么会如此呢?我也注意到,我使用的编辑器(Sublime)并没有改变最后一个的颜色,就像其他人一样。我将长度函数作为对象的一部分,以便我可以调用myObjectInstance。 myAssociativeArray并获得一个长度。 任何帮助将非常感激!

+0

你是如何调用控制台日志?通常如果你得到函数的打印版本,因为你实际上并没有执行函数,而是引用它,即'console.log(someObject.myFunc)'而不是'console.log(someObject.myFunc())' –

+0

第一个和平'this.users'或'this.myAocociativeArray'?你怎么调用函数:'myObject.myAssociativeArrayLen'或'myObject.myAocociativeArrayLen()'? –

回答

1

在您的console.log中,您可能没有真正运行该功能,而只能引用它。

console.log(myObject.myAssociativeArrayLen()); 

VS(我认为你正在做的)

console.log(myObject.myAssociativeArrayLen); 
0

您正在试图确定哪些应该被隐式调用的属性。 在这种情况下,您需要使用getter功能。
但是getter不应该与函数构造函数一起使用,因为您可以编写在所有实例之间共享的等效原型方法。
但你仍然可以添加下面的方式,吸气:

function myObject(myInput) { 
    this.myValue = myInput; 
    this.myAssociativeArray = {}; 
    Object.defineProperties(this, { 
      "myAssociativeArrayLen" : { //add the myAssociativeArrayLen property to this instance 
       "get" : function() {//define getter 
        //your logic 
        return smthing; 
       }, 
      } 
     }); 
} 
var x = new myObject(5); 
alert(x.myAssociativeArrayLen);//implicitly invoke the associated getter function 
相关问题