为什么在调用函数属性时这是未定义的?

时间:2017-12-15 12:40:49

标签: javascript function object properties

这是我的代码:



function myOuterFunction() {

    myInnerFunction();

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


    function myInnerFunction(){

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

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




为什么我无法使用函数属性?

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

由于

2 个答案:

答案 0 :(得分:2)

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



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




答案 1 :(得分:0)

你的错误是 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();