2013-02-24 44 views
1

我已经在前端使用coffeescript几年了。而我所熟悉的类语法看起来像这样:Coffeescript类语法在节点中有何不同?

class MyClass 
     methodOne : -> 
     console.log "methodOne Called" 
     methodTwo : (arg, arrg) -> 
     console.log "methodTwo Called" 

最近我一直在玩节点和frappe样板与CoffeeScript中和节点的Web应用程序。

使用CoffeeScript中类的语法如下路线这个脚本:

class MyClass 
     @methodOne = -> 
     console.log "methodOne Called" 
     @methodTwo = (arg, arrg) -> 
     console.log "methodTwo Called" 

唯一的区别使用,我可以从我的正常使用请注意,是该文件Routes.coffee消费类,而不是直接制作new对象。所以:

MyClass.methodOne() 

    # vs 

    new MyClass().methodOne() 

现在我明白了,而其他的语法是否@methodOne语法不使用.prototype。但是,为什么这会导致使用失败?

回答

2

因此,以@开头的方法是其中一切都是实例方法的类方法。使用实例方法,:本质上意味着公开,其中=表示私有。 CoffeeScript中的类方法不存在“公共”与“私人”二分法,因此:=做了一些事情。他们都是公开的。

例如,看看这个类:

class MyClass 
    @methodOne = -> 
    @methodTwo : -> 
    methodThree : -> 
    methodFour = -> 

计算结果为以下JavaScript:

var MyClass; 

MyClass = (function() { 
    var methodFour; 

    function MyClass() {} 

    MyClass.methodOne = function() {}; 
    MyClass.methodTwo = function() {}; 
    MyClass.prototype.methodThree = function() {}; 
    methodFour = function() {}; 

    return MyClass; 

})(); 

所以,methodOnemethodTwo都是公共类的方法,methodThree随便去哪儿在原型上,所以它是一个公共实例方法,并且methodFour成为类中的一个变量,可以在内部使用,但永远不会公开公开地公开。

希望能回答你的问题?

相关问题