関数の引数名と同じスロットを挿入するinitメソッドを作ってみた。
Function.prototype.init = function(obj,arg){
var slot = this.toString().match(/\(([^)]*)/)[1].split(/, /);
for(var i=0;i<arg.length;i++) obj[slot[i]] = arg[i];
}これは、こんな処理を、
function Foo(aaa,bbb,ccc){
this.aaa = aaa;
this.bbb = bbb;
this.ccc = ccc;
}
function Bar(ddd,eee){
this.ddd = ddd;
this.eee = eee;
}
foo = new Foo(1,2,3);
bar = new Bar(4,5);こう書いて済まそうとするもの。
function Foo(aaa,bbb,ccc){
Foo.init(this,arguments);
}
function Bar(ddd,eee){
Bar.init(this,arguments);
}
foo = new Foo(1,2,3);
bar = new Bar(4,5);おぼえがき
関数Foo内でのthisは、newしようとしているオブジェクト
initメソッド内でのthisは、関数オブジェクトFoo自体
argumentsオブジェクトのconstructorは直接function Object(){}になっており、Arguments.prototype等は存在しない。