How to return settings from an object

笑着哭i 提交于 2019-12-11 14:08:36

问题


i have done something like this:

myProject =

  settings:
    duration: 500
    value: 'aValue'

  aFunction: ->
    myElement.fadeOut myProject.settings.duration

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)

I tried with

getSetting: (param) ->
  myProject.settings.param

but failed? Why is that? Thank you!


回答1:


To access an object property by a variable, you can do:

object[key]

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)

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);


来源:https://stackoverflow.com/questions/12797014/how-to-return-settings-from-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!