coffeescript+prototypejsはnodejsを編纂して更にruby-likeに似ています.
4013 ワード
まずprototype for nodejsをインストールします.
参照
npm install prototype
例を見ます
参照
npm install prototype
例を見ます
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!
Class.creat Taes in arbitrry number of argments.The first-if it is an other class-defines the new class shast inhers from it.All other argments aradded as instance meths;internally they are subsequent cals to addMethods.This can convently be used for mixing in modules:#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
coffeescript自体もカテゴリ別の実装をカスタマイズしました.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, "-"
上のコードをjsに変換した後、前と後を比較して、coffeescriptコードの量が少なくなりました.私自身はcoffeescript方式の声明類に向いています.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, "-");
};