[英]Methods for Class 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;
})();
方法greetings和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)
其他位置(按相同的編譯結果排序)
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
構造的上下文中,方法定義會受到@
(此)的使用的影響。 這是一個簡單的例子:
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"
盡管語法略有不同,但最新的兩個具有相同的編譯結果。
:
是指一類塊內?” 它用於定義屬性。 當使用=
(等號)代替時,將定義“專用”變量。
:
指(構造)方法里面? 外面一類的水平(例如頂級代碼,函數,構造等內) :
不具有“特殊類”的意思。 :
是對象文字中鍵名對之間的分隔符。
您提供的代碼@upperName: -> ...
無效,並且無法在最新的CoffeeScript版本中進行編譯。 upperName: -> ...
雖然有效,但將編譯為具有屬性upperName
和函數作為值的對象文字。
看一下已編譯的CoffeeScript代碼 :
var ClassObject;
ClassObject = (function() {
var privateVar;
function ClassObject() {}
ClassObject.prototype.instanceMethod = function() {};
ClassObject.classMethod = function() {};
ClassObject.classMethod2 = function() {};
privateVar = "private";
return ClassObject;
})();
帶有您編寫的縮進的代碼無法編譯。 我認為這是您的意思:
class Animal
constructor: (name) ->
@name = name
upperName: ->
@name.toUpperCase()
greetings: ->
console.log "Hello #{@name}"
如果進行編譯,則輸出應該更有意義。 如果我們使用以下代碼運行它:
a = new Animal 'panda'
console.log a.name
console.log a.upperName()
a.greetings()
我們得到預期的輸出:
panda
PANDA
Hello panda
類定義類似於普通的對象定義-它們是一組屬性和值。 在這種情況下,我們將動物定義為一組3個屬性,它們都是函數(構造函數,upperName和greetings)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.