Javascript コンストラクタ・プロトタイプ
前に買った、オブジェクト指向Javascriptという本を使って
勉強中。
- 作者: Stoyan Stefanov,水野貴明,渋川よしき
- 出版社/メーカー: アスキー・メディアワークス
- 発売日: 2012/04/13
- メディア: 大型本
- 購入: 1人 クリック: 124回
- この商品を含むブログ (1件) を見る
node.jsやりたいんだけどまずJavascriptの基礎を固めておかないと
ついていけねえ。。。と思ったので。
勉強の為に書いたコードを自分のメモ代わりに載せておく。
あとで見返せるように。。。
//5.1 コンストラクタ 特殊なプロパティ //[持っている内容] //--------------------- //arguments: //引数 //caller: //どの関数から呼ばれたか //length: //要素数 //name: //関数名 function test(a,b,c){ return a * b; } console.log("テスト関数 length:" + test.length ); console.log("コンストラクタ:" + test.constructor ); //5.1 プロトタイプ function Gadget(name, color){ this.name = name; this.color = color; this.whatAreYou = function(){ return 'I am a ' + this.color + ' ' + this.name; } } //関数に、プロパティを追加できる。 Gadget.prototype.price = 100; //プロパティ追加 Gadget.prototype.rating = 3; Gadget.prototype.getInfo = function(){ return 'Rating: ' + this.rating + ', price:' + this.price; }; //メソッドを追加 var g = new Gadget( 'aren', 'red' ); console.log( "プロトタイプ price:" + g.price ); console.log( "プロトタイプ raitng:" + g.rating ); console.log( "プロトタイプ name:" + g.name ); console.log( "プロトタイプ getInfo:" + g.getInfo() ); Gadget.prototype.get = function(what){ return this[what]; }; console.log( "プロトタイプ get:" + g.get('price') ); //関数内のプロパティを探してなければprototypeのプロパティを検索する //優先順位は、関数内のプロパティ > prototypeのプロパティ