2016-11-29 71 views
0

有谁能够说我,为什么这样的功能不会被执行的处理:JS功能不是从模块

var textStyle = { 
     color: function() { 
      console.log('test') 
      return 'red' 
      } 
     } 
} 

但这个工作得很好:

var textStyle = { 
      color: test() 
      } 
    } 

function test() { 
    console.log('test'); 
     return 'red' 
    } 
+4

第一个将'textStyle.color'的值设置为函数,第二个将它设置为运行该函数的结果。 – Phylogenesis

+0

ahh ..好像没有回调,事后调用函数。谢谢! –

+0

如果你想使用匿名函数 – Phylogenesis

回答

1

我已经通过添加评论你的代码向你展示每一行发生了什么,以及为什么你会看到你所看到的行为。

// 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() 
} 

注意,在这种情况下,我们调用该函数。

0

然后你要做的textStyle.color()

颜色是没有功能的结果。

color:test()将是什么测试返回的,而不是实际的函数。

你似乎也有一个额外的'}'。