【问题标题】:Set function property from within object literal从对象字面量中设置函数属性
【发布时间】:2018-03-28 17:58:17
【问题描述】:

我声明tasks对象:

var tasks = {

    test: () => {
        /// ....
    }

};

test 函数中,我想设置tasks.test.description 属性。到目前为止,我已经尝试过:

var tasks = {
    test: () => {
        // need to set tasks.test.description here
        // 
        // tried without success:
        // tasks.test.description = '...';
        // this.description = '...';
        // arguments.callee.description = '...';
    }
};

还有:

var tasks = {
    test: function xxx() {
        // all methods from example above, plus:
        // xxx.description = '...';
    }
};

从函数范围外访问时,描述总是未定义。

console.log(tasks.test.description); // => undefined

有没有办法在对象字面量的函数定义中设置描述属性?

【问题讨论】:

  • 要了解您在做什么,请发帖Minimal, Complete, and Verifiable example
  • tasks.test.description 要走的路。会起作用的。
  • 你意识到函数中的代码只是在函数被调用时运行?
  • 拜托,你需要澄清你想要做什么!
  • @Ele 我正在尝试声明一个对象并将test 属性设置为一个函数,并将该函数的description 属性设置为一个字符串。我想通过使用一个语句(上面粘贴的对象声明)来做到这一点。如果这是不可能的,我可以接受,不需要仅仅因为答案是“不”而投反对票。

标签: javascript node.js ecmascript-6


【解决方案1】:

可能使用 Object.assign 将函数与对象结合起来:

 test: Object.assign(() => {
    /// ....
  }, {
   description: "whatever"
 })

【讨论】:

  • 等一下,OP 这么说:在测试函数中,我想设置 tasks.test.description 属性。这如何回答这个问题?
  • @ele OP 想要什么是不可能的。
  • 我完全同意你的看法,但是,这个答案没有帮助。我认为,您可以输入该信息并对此替代方案进行参考。
  • 似乎是最有创意的答案,尽管我的问题可能有些不准确。
  • 呵呵呵呵不清楚的问题导致不明确的接受答案:)...祝你有美好的一天!!!
【解决方案2】:

您的第一种方法几乎是正确的,但您必须调用该函数才能执行任何操作。

var tasks = {
  test: () => {
    tasks.test.description = '...';
  }
};
tasks.test();
console.log("The value of tasks.test.description is " + tasks.test.description);

【讨论】:

    【解决方案3】:

    console.log(tasks.test.description); 的原因返回 undefined 是你定义的对象,但描述属性将被创建,直到你第一次运行 tastks.test() 方法。要向对象方法添加属性描述,请尝试以下操作:

    const tasks = {
      test() {
        //....
      }
    };
    
    tasks.test.description = 'asd';
    

    或者

    const tasks = {
      test() {
        this.test.description = 'asd';
      }
    };
    
    tasks.test();
    
    console.log(tasks.test.description);
    

    【讨论】:

      【解决方案4】:

      你的一个尝试几乎是正确的。您只需要调用tasks.test() 来设置tasks.test.description

      var tasks = {
          test: function xxx() {
              xxx.description = '...';
          }
      };
      
      tasks.test();
      console.log(tasks.test.description);

      如果您想设置该属性而不调用 test the answer by Jonas W. 是要走的路。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        相关资源
        最近更新 更多