オブジェクト指向プログラミングをしやすくする
普通の書き方。
var Apple = function() { this.initialize(); }; Apple.prototype.initialize = function() { alert("init"); }; new Apple();
applyを使ってみる。var Appleに入るのはprototype.jsのCrass.create()で渡されるクロージャと同じ。
var Apple = function() { this.initialize.apply(this, arguments); }; Apple.prototype.initialize = function() { alert("init"); }; new Apple();
クラスを定義して拡張する形にする。これでClass.createでクラス生成してClass.extendで拡張できる。
var Class = {}; Class.create = function() { var func = function() { this.initialize.apply(this, arguments); }; func.extend = function(data) { for (var i in data) { this.prototype[i] = data[i]; } return this; }; return func; }; var Apple = Class.create(); Apple.extend({ initialize: function() { alert("init"); }, test: function() { alert("test"); } }); var r = new Apple(); r.test();