【问题标题】:Why is this undefined when I call a functions property?为什么当我调用函数属性时这是未定义的?
【发布时间】:2017-12-15 12:40:49
【问题描述】:

这是我的代码:

function myOuterFunction() {

    myInnerFunction();

    var myObject = {say: myInnerFunction.myProperty1,
                  say2: myInnerFunction.myProperty2
                };


    function myInnerFunction(){

      return {myProperty1: "hello",
              myProperty2: "world"
             };
    }
    

console.log(myObject);
}
myOuterFunction();

为什么我无法获取函数属性?

我知道我可以用另一个变量来解决这个问题,但为什么这个解决方案不可行?

谢谢

【问题讨论】:

  • 调用函数...
  • 调用myInnerFunction() 不会神奇地将返回值应用到函数本身。您需要将返回值分配给某物(var properties = myInnerFunction()),然后访问返回值(properties.myProperty1)。
  • myInnerFunction 指的是函数对象本身,而不是调用时返回的值。不过你可以做myInnerFunction().myProperty1

标签: javascript function object properties


【解决方案1】:

你应该在使用之前存储函数的值。

function myOuterFunction() {
  var data = myInnerFunction();
  var myObject = {
    say: data.myProperty1,
    say2: data.myProperty2
  };
  function myInnerFunction() {
    return {
      myProperty1: "hello",
      myProperty2: "world"
    };
  }
  console.log(myObject);
}
myOuterFunction();

【讨论】:

    【解决方案2】:

    你的错误是 1) 尽量不要在 myOuterFunction() 中使用 myInnerFunction()。这不是一个好的编程习惯 2) 在公开调用 myInnerFunction() 时,它什么也不做。您甚至没有将其返回值赋予变量。 3) 在没有 () 的情况下调用 myInnerFunction 不会告诉 javascript 它是一个函数

    你应该这样写

    function myOuterFunction() {
        var myObject = {say: myInnerFunction().myProperty1,
                          say2: myInnerFunction().myProperty2
                        };
    
        console.log(myObject);
    }
    function myInnerFunction(){
    
          return {myProperty1: "hello",
                  myProperty2: "world"
                 };
    }
    myOuterFunction();
    

    【讨论】:

    • 谢谢!我应该始终避免在函数中实现函数吗?
    • javascript 没有任何问题,但如果你不这样做,这是一个更好的做法。因为这将成为一种习惯,您将在其他编程语言中使用它,这会导致错误。这只是一个建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2013-01-18
    • 2020-03-03
    • 2011-03-15
    • 1970-01-01
    相关资源
    最近更新 更多