我已经通过添加评论你的代码向你展示每一行发生了什么,以及为什么你会看到你所看到的行为。
// define a variable textStyle as an object
var textStyle = {
// with the property color, that refers to the following function
color: function() {
console.log('test')
return 'red'
}
}
在这段代码中,我们没有任何地方调用分配给颜色的函数。
现在第二个片段,我已经改变了,以使其更清晰一点(这是真正在JavaScript中发生的 - 功能定义悬挂)
//define a function called test
function test() {
console.log('test');
return 'red'
}
//define a variable textStyle as an object
var textStyle = {
// with a property color, that refers to **the result** of calling the test function
color: test()
}
注意,在这种情况下,我们是调用该函数。
第一个将'textStyle.color'的值设置为函数,第二个将它设置为运行该函数的结果。 – Phylogenesis
ahh ..好像没有回调,事后调用函数。谢谢! –
如果你想使用匿名函数 – Phylogenesis