我是 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;
})();
方法greetings和upperName有什么区别???
“:”在类里面做什么?
谢谢
最佳答案
符号汇总(左=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/