![](/img/trans.png)
[英]Why is this callback undefined when I abstract my functions to named functions?
[英]Why is this undefined when I call a functions property?
这是我的代码:
function myOuterFunction() { myInnerFunction(); var myObject = {say: myInnerFunction.myProperty1, say2: myInnerFunction.myProperty2 }; function myInnerFunction(){ return {myProperty1: "hello", myProperty2: "world" }; } console.log(myObject); } myOuterFunction();
为什么我无法了解functions属性?
我知道我可以用另一个变量来解决这个问题,但是为什么不能解决这个问题呢?
谢谢
您应该在使用函数之前存储该函数的值。
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)尽量不要在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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.