javascript - 类 coffeescript 的方法

标签 javascript coffeescript

我是 coffeescript 的新手,也是 javascript 对象的新手。 我在 coffeescript 中有这段代码:

class Animal
constructor: (name) ->
    @name = name
    @upperName: ->
        @name.toUpperCase()
    @greetings ->
        console.log 'Hello %s', @name

this.type = 'Animal'

这是“编译”到这个 javascript 中的:

var Animal
Animal = (function() {
function Animal(name) {
  this.name = name;
  ({
    this.upperName: function() {
      return this.name.toUpperCase();
    }
  });
  this.greetings(function() {
    return console.log('Hello %s', this.name);
  });
}
Animal.type = 'Animal';
return Animal;
})();

方法greetingsupperName有什么区别???
:”在类里面做什么?

谢谢

最佳答案

符号汇总(左=CS,右=JS)

Animal 类 中:

identifier: value        Animal.prototype.identifier = value
@identifier: value       Animal.identifier           = value
@identifier= value       Animal.identifier           = value
identifier = value       identifier                  = value  (private var)

其他地方(按相同的编译结果排序)

Animal::identifier = value  Animal.prototype.identifier = value
Animal.identifier  = value  Animal.identifier           = value
identifier = value          identifier                  = value
// New:
@identifier = value         this.identifier             = value
identifier: value           { identifier: value}                 (object literal)
@identifier: value          ---INVALID---

在 CoffeeScript 中,@ 编译为 this

class 构造的上下文中,方法定义受使用 @ (this) 的影响。这是一个简单的例子:

class ClassObject
    instanceMethod: ->
        # This method will be defined on the prototype (available to instance)

    @classMethod: ->
        # This method is defined on the class object itself, not on the instance

    this.classMethod2 = -> # See previous and below
    privateVar = "private"

虽然语法略有不同,但最新的两个编译结果是一样的。

: 在类 block 中是什么意思?”

它用于定义属性。当使用 =(等号)代替时,将定义一个“私有(private)”变量。

: 在(构造函数)方法中是什么意思?

在类的层级之外(例如顶级代码、函数内部、构造函数等),: 没有“特殊类”的含义。 : 是对象字面量中键名对之间的分隔符。
您给定的代码 @upperName: -> ... 无效,并且无法在最新的 CoffeeScript 版本中编译。 upperName: -> ... 是有效的,并且将编译为具有属性 upperName 和函数作为值的对象文字。


看看 compiled CoffeeScript code :

var ClassObject;

ClassObject = (function() {
  var privateVar;

  function ClassObject() {}

  ClassObject.prototype.instanceMethod = function() {};

  ClassObject.classMethod = function() {};

  ClassObject.classMethod2 = function() {};

  privateVar = "private";

  return ClassObject;

})();

关于javascript - 类 coffeescript 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12843579/

相关文章:

javascript - Cappuccinos objc_msgSend() 与普通 JavaScript 调用的速度比较?

jquery - CoffeeScript 和 jQuery.post() 成功 : callback

function - Coffeescript中的多行函数调用

javascript - 单击 Select 元素时传递选项

javascript - 尝试移动两个 div 的 onkeydown 时出现问题

javascript - 使用选项下拉列表过滤数据 foreach 渲染 View ,BatmanJS

javascript - Coffeescript 在给定该类的对象的情况下创建该类的新实例

jquery - 如何在 Jquery 和 CoffeeScript 中迭代选择元素的选项?

javascript - 从我的greasemonkey脚本中监听一个事件

JavaScript "is not a function"问题