如何从对象返回设置 [英] How to return settings from an object
问题描述
我做了这样的事:
myProject =
settings:
duration: 500
value: 'aValue'
aFunction: ->
myElement.fadeOut myProject.settings.duration
这只是一个示例,像那样。很多时候,我必须参考设置获得一定的值,我总是写 myProject.settings.value
,它不看起来不错。
This is just a sample but my project is like that. A lot of times i have to reference to the settings to get a certain value, and i always have to write myProject.settings.value
, and it doesn´t look good.
我的问题是,我可以调用一个函数来返回想要的值吗?这样的东西:
My question is, can I call a function that returns the wanted value? Something like this:
aFunction: ->
myElement.fadeOut getSetting(duration)
我尝试使用
getSetting: (param) ->
myProject.settings.param
但失败?这是为什么?
谢谢!
but failed? Why is that? Thank you!
推荐答案
要通过变量访问对象属性,您可以:
To access an object property by a variable, you can do:
object[key]
在coffeescript中,最后一行应该是返回值,在您的示例中:
请注意@(= this)。
In coffeescript, the last line should be the return value, in your example: Please note the @ (= this).
myProject =
settings:
duration: 500
value: 'aValue'
fadeOut: ($element) ->
$element.fadeOut @getSetting('duration')
getSetting: (key) ->
@settings[key]
myProject.fadeOut($myElement)
javascript:
The javascript :
var myProject;
myProject = {
settings: {
duration: 500,
value: 'aValue'
},
fadeOut: function($element) {
return $element.fadeOut(this.getSetting('duration'));
},
getSetting: function(key) {
return this.settings[key];
}
};
myProject.fadeOut($myElement);
这篇关于如何从对象返回设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!