CoffeeScript為對象生成動態變量名(命名類)

[英]CoffeeScript generating dynamic variable names for objects (named classes)


I'm pretty new to the world of JavaScript and even newer to CoffeeScript. I have a problem and I'm not sure if it's even possible.

我對JavaScript的世界是陌生的,甚至更新到CoffeeScript。我有一個問題,我不確定是否有可能。

Say I have a CoffeeScript class like this

假設我有一個這樣的CoffeeScript類

class @Model
  constructor: (@name) ->

how could I pass the names of models to be created to a function to instantiate these objects whilst appending the name of the variable [in this case] with _model? Something like:

如何將要創建的模型的名稱傳遞給要實例化這些對象的函數,同時在_model中附加變量的名稱[在本例中]?喜歡的東西:

makeModel = (name) ->
  "#{name}_model" = new Model(name)

My rails app tells me that:

我的rails應用告訴我:

unexpected =
      "#{name}_model" = new Model(
                ^

I'm assuming that this is because of the string. Is there some sort of method to convert a string to a variable name? I took a quick look at the .eval() method but the little book of CoffeeScript warns against it's use.

我假設這是因為弦。是否有某種方法可以將字符串轉換為變量名?我快速地查看了.eval()方法,但是CoffeeScript小書警告不要使用它。

Thanks

謝謝

1 个解决方案

#1


2  

You could do something like this:

你可以這樣做:

ModelFactory = do -> 
  class @Model
    constructor: (@name) ->

  models = {}

  makeModel = (name) ->
    model = new Model(name)
    models["#{name}Model"] = model
    model

  getModel = (name) ->
    models["#{name}Model"] or makeModel(name)

  { getModel }

Secret Magic:

do -> - The do keyword creates an IIFE, a function that is called as soon as it is created. It can be used for creating modules like the following:

do ->——do關鍵字創建一個IIFE,該函數在創建時就會被調用。可用於創建如下模塊:

var myModule = (function () {
    var privateFunc = function () {};
    var publicFunc = function () { privateFunc(); };
    return {
        publicFunc: publicFunc
    }
})();

accessing properties with strings - In JavaScript, you can access a property of an object as a string, by using the square-bracket ([]) notation, plus a string, or a variable containing a string. Here we are combining this with the CoffeeScript string interpolation sugar ("#{}") to dynamically create property names and assign them.

使用字符串訪問屬性——在JavaScript中,可以通過使用方括號([])符號,加上字符串或包含字符串的變量,將對象的屬性作為字符串訪問。在這里,我們將它與CoffeeScript字符串插值sugar(“#{}”)相結合,以動態創建屬性名並分配它們。

var object = {
    prop: 'value',
    otherProp: 'otherValue'
};

var propertyName = 'prop';
var value = object[propertyName]; // 'value';

var something = 'Something'
object['my' + something] = 'a new property';
object.mySomething === 'a new property'; // true

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/04/08/72f3abb9365e8fe1fa0e58e871e4e56b.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com