简体   繁体   English

使用动态名称初始化对象-coffeescript / node.js / javaScript

[英]Initialising an object with dynamic name - coffeescript/node.js/javaScript

I am attempting to build a plugin system where I do not know the plugins beforehand. 我正在尝试构建一个我事先不知道插件的插件系统。 Initialising an object using 'require' from browserify. 使用browserify中的“ require”初始化对象。 As follows: 如下:

class.coffee:

   class MyClass
    name: "my-class"
    constructor: ->

    @getName: ->
        return @name

  exports.plugin = new MyClass

Then from the calling file I have: 然后从调用文件中我有:

pluginName = # from a config file
{ plugin } = require './#{pluginName}.coffee'
console.log plugin
console.log plugin.getName()

The first logger call gives me: 第一个记录器调用给我:

MyClass{ name="my-class" }

The second one fails however with plugin.getName is not a function. 第二个失败,但是plugin.getName不是一个函数。

Any help/guidance appreciated. 任何帮助/指导表示赞赏。 I'm not a JS developer and am new to coffeescript/node.js as well. 我不是JS开发人员,并且也是coffeescript / node.js的新手。

Thanks. 谢谢。

You should not have the @ before getName . getName之前不应该使用@

Having the @ is equivalent to this in JS 在JS中具有@等效于此

MyClass.getName = function(){
  return this.name;
};

But in this case, getName is a function on the class itself, not the MyClass instance. 但是在这种情况下, getName是类本身的函数,而不是MyClass实例。

Without the @ , like this, getName: -> the JS is like this: 没有@ ,像这样, getName: -> JS像这样:

MyClass.prototype.getName = function(){
  return this.name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM