日期:2014-05-16 浏览次数:20319 次
prototype = require 'prototype' Object.extend global, prototype (9).times (x)-> console.log x [1,2,3,4].each (x)-> console.log x Person = Class.create #定义一个类 initialize: (name)-> @name = name say: (message)-> "#{@name}:#{message}" Pirate = Class.create Person, #继承父类 say: ($super, message)-> "#{$super message}, yarr!" john = new Pirate 'Long John' console.log john.say 'ahoy matey' #输出Long John:ahoy matey, yarr!
#define a module Vulnerable = wound: (hp)-> @health -= hp @kill() if @health < 0 kill: -> @dead = true #the first argument isn't a class object, so there is no inheritance ... #simply mix in all the arguments as methods: Person2 = Class.create Vulnerable, initialize: -> @health = 100 @dead = false bruce = new Person2 bruce.wound 55 console.log bruce.health #=> 45
class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" sam.move() tom.move() String::dasherize = -> this.replace /_/g, "-"
var Animal, Horse, Snake, sam, tom, __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function(meters) { return alert(this.name + (" moved " + meters + "m.")); }; return Animal; })(); Snake = (function(_super) { __extends(Snake, _super); function Snake() { Snake.__super__.constructor.apply(this, arguments); } Snake.prototype.move = function() { alert("Slithering..."); return Snake.__super__.move.call(this, 5); }; return Snake; })(Animal); Horse = (function(_super) { __extends(Horse, _super); function Horse() { Horse.__super__.constructor.apply(this, arguments); } Horse.prototype.move = function() { alert("Galloping..."); return Horse.__super__.move.call(this, 45); }; return Horse; })(Animal); sam = new Snake("Sammy the Python"); tom = new Horse("Tommy the Palomino"); sam.move(); tom.move(); String.prototype.dasherize = function() { return this.replace(/_/g, "-"); };