Classes in CoffeeScript
Classes in CoffeeScript
CoffeScript中有以下类:
class MyClass
f: (@x) ->
在JS中翻译此代码我们有:
(function() {
var MyClass;
MyClass = (function() {
function MyClass() {}
MyClass.prototype.f = function(x) {
this.x = x;
};
return MyClass;
})();
}).call(this);
我不明白为什么为了给MyClass添加函数,我应该使用原型;为什么我不能使用'MyClass.f=函数(x(。。。"?请给我解释一下。谢谢。
如果定义
class MyClass
f: (@x) ->
@g: (@x) ->
m = new MyClass()
您会发现,MyClass
具有g
属性,但没有f
,而m
具有f
属性,但不具有g
属性。
要从m
访问g
,必须使用m.constructor.g
。
也称为MyClass.prototype == m.__proto__
。
要真正理解这一点,您需要深入研究Javascript的原型继承结构。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
当代码new foo(…(被执行时,会发生以下事情:
创建了一个新对象,继承了foo.prototype.
构造函数foo是用指定的参数调用的。。。
构造函数返回的对象将成为整个新表达式的结果。。。
因此,关键是新对象从类prototype
继承(实际上是的副本(。
您不必使用原型链,也可以分配静态方法,如下所示:
class MyClass
@f: (@x) ->
将输出:
var MyClass;
MyClass = (function() {
function MyClass() {}
MyClass.f = function(x) {
this.x = x;
};
return MyClass;
})();
相关文章:
- Node.js's Buffer.writeFloatBE in Javascript
- Setting default onclick behavior for <img> tag in gene
- Lucene Search in Alfresco
- grep in JQuery to C#
- write HTML in JavaScript
- jQuery setTimeOut: in for-loop
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- HTMLInputElement in IE7
- Mongodb$in以与数组中相同的顺序获取结果
- element.dataset in Internet Explorer
- jQuery parent() in table
- Instagram oauth flow in angularjs
- In循环的In运算符前后
- CoffeeScript 在 'for v in values' 中创建一个全局变量 'v',导致事件中的错误引用
- CoffeeScript in server/server.coffee won't execute
- beginPath() in Coffeescript?
- n-ary curry in CoffeeScript
- Classes in CoffeeScript
- ?= vs ||= in CoffeeScript