【问题标题】:How to stop a function from being treated as a property in a javascript object?如何阻止函数被视为 javascript 对象中的属性?
【发布时间】:2015-02-26 10:39:03
【问题描述】:

我在 javascript (Node.js,如果重要的话) 应用程序中有以下对象。

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 并得到一个长度。 任何帮助将不胜感激!

【问题讨论】:

  • 你怎么调用控制台日志?通常,如果您获得函数的打印版本,因为您实际上并没有执行该函数,而是引用它,即 console.log(someObject.myFunc) 而不是 console.log(someObject.myFunc())
  • 第一次和平this.users还是this.myAssociativeArray?以及如何调用函数:myObject.myAssociativeArrayLenmyObject.myAssociativeArrayLen()

标签: javascript class object methods properties


【解决方案1】:

您正在尝试定义一个应该被隐式调用的属性。 在这种情况下,您需要使用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

【讨论】:

    【解决方案2】:

    可能在您的 console.log 中,您实际上并没有运行该函数,您可能只是在引用它。

    console.log(myObject.myAssociativeArrayLen());
    

    vs(我认为你在做什么)

    console.log(myObject.myAssociativeArrayLen);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2013-10-11
      • 2023-02-16
      相关资源
      最近更新 更多