简体   繁体   English

如何从coffeescript中的静态方法访问类属性

[英]How to access class properties from static methods in coffeescript

I have such code 我有这样的代码

class Class
  property: 5

  @run: ->
    console.log @property

Class.run()

How can I make property value appear in the console, considering all I can change is @run contents? 考虑到我只能更改@run内容,如何使property值出现在控制台中?

Corresponding jsFiddle 对应的jsFiddle

The code you provided compiles to : 您提供的代码编译为:

var Class;

Class = (function() {
  function Class() {}

  Class.prototype.property = 5;

  Class.run = function() {
    return console.log(this.property);
  };

  return Class;

})();

Class.run();

You can see that property is attached to the prototype of Class , not the class itself. 您会看到该property附加到Class的原型上,而不是该类本身。 Thus, to access it you can use the :: in CoffeeScript which is syntastic sugar to access the prototype of a class. 因此,要访问它,您可以在CoffeeScript中使用:: ,它是合成糖,用于访问类的原型。

Class::property

Otherwise, if you really want a static property (which is not the case here), declare it that way: 否则,如果您确实需要静态属性(此处不是这种情况),请以这种方式声明:

class Class
  @property: 5

Use Class::property 使用Class::property

class Class
    property: 5

    @run: ->
        console.log(Class::property)

Class.run()

访问类属性:

Class::property

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

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