简体   繁体   中英

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?

Corresponding 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. Thus, to access it you can use the :: in CoffeeScript which is syntastic sugar to access the prototype of a class.

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 Class
    property: 5

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

Class.run()

访问类属性:

Class::property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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