ras*_*cio 1 javascript coffeescript
我是coffeescript的新手,也是javascript中的对象.我在coffeescript中有这段代码:
class Animal
constructor: (name) ->
@name = name
@upperName: ->
@name.toUpperCase()
@greetings ->
console.log 'Hello %s', @name
this.type = 'Animal'
Run Code Online (Sandbox Code Playgroud)
这是"编译"到这个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;
})();
Run Code Online (Sandbox Code Playgroud)
方法问候和upperName有什么区别???
" : "在课堂上做什么?
谢谢
内class Animal:
identifier: value Animal.prototype.identifier = value
@identifier: value Animal.identifier = value
@identifier= value Animal.identifier = value
identifier = value identifier = value (private var)
Run Code Online (Sandbox Code Playgroud)
其他地方(按相同的编译结果排序)
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---
Run Code Online (Sandbox Code Playgroud)
在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"
Run Code Online (Sandbox Code Playgroud)
虽然语法略有不同,但最新的两个具有相同的编译结果.
:在一个班级里面意味着什么?"它用于定义属性.当使用=(等号)时,将定义"私有"变量.
:(构造函数)方法中的含义是什么?在类的级别之外(例如顶级代码,函数内部,构造函数等),:没有"特殊类"的含义.:是对象文字中键名对之间的分隔符.
您的给定代码@upperName: -> ...无效,并且无法在最新的CoffeeScript版本中编译.upperName: -> ...虽然有效,但将编译为具有属性upperName和函数作为值的对象文字.
var ClassObject;
ClassObject = (function() {
var privateVar;
function ClassObject() {}
ClassObject.prototype.instanceMethod = function() {};
ClassObject.classMethod = function() {};
ClassObject.classMethod2 = function() {};
privateVar = "private";
return ClassObject;
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |