closure = do -> _private = "foo" -> _private console.log(closure()) #=> "foo" //`do`关键词能够产生一个`Immediate Function` (function() { var closure; closure = (function() { var _private; _private = "foo"; return function() { return _private; }; })(); console.log(closure()); }).call(this);
CoffeeScript
使用特殊的=>
语法省去了这个麻烦element = document.getElementById('id') @clickHandler = -> alert "clicked" element.addEventListener "click", (e) => @clickHandler(e) // (function() { var element; element = document.getElementById('id'); this.clickHandler = function() { return alert("clicked"); }; element.addEventListener("click", (function(_this) { return function(e) { return _this.clickHandler(e); }; })(this)); }).call(this);
String::expends = -> @replace /_/g, "-" // (function() { String.prototype.expends = function() { return this.replace(/_/g, "-"); }; }).call(this);
class Person _private = 'value' //private @sex: true //Person.sex @log: -> //Person.log console.log 0 @create: (name, age)-> new Person(name,age) constructor: (@name, @age) -> log: -> //instance.log console.log @name tell: => //instance.tell console.log @age jinks = new Person('jinks', 23) jack = Person.create('jack', 22)
constructor是构造函数,必须用这个名称ruby
构造函数中若是给实例变量赋值,直接将@name写在参数中便可,等价于在函数体中的@name = name闭包
对于实例方法,要用=>来绑定this,这样能够做为闭包传递iphone
class Gadget constructor: (@name) -> sell: => "buy #{@name}" class Iphone extends Gadget constructor: -> super("iphone") nosell: => "Don't #{@sell()}" iphone = new Iphone iphone.nosell()
在ruby语言中的Mixin,可以让你的类得到多个模块的方法,能够说是对多重继承一种很好的实现函数
class Module @extend: (obj) -> for key, value of obj @[key] = value @include: (obj) -> for key, value of obj @::[key] = value classProperties = find: (id) -> console.log ("find #{id}") instanceProperties = save: -> console.log ("save") class User extends Module @extend classProperties @include instanceProperties user = User.find user = new User user.save()