Created
July 25, 2015 11:23
-
-
Save Bambina-zz/7e190da7066d21c67e72 to your computer and use it in GitHub Desktop.
js create object with new Object()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//引数に名前をとるコンストラクタ関数を定義する。 | |
//この関数はnew演算子で呼び出し、オブジェクトを生成できる。 | |
var Person = function(name){ | |
this.name = name; | |
} | |
//Person関数のプロトタイプに、outPutを定義し、 | |
//名前を出力する処理をもつ無名関数を代入する。 | |
//クラスメソッドにあたる処理をプロトタイプに定義することで、 | |
//Person関数で生成された複数のオブジェクトがこのメソッドを共有できる。 | |
//オブジェクトの生成ごとにoutputName関数が生成されず、メモリ資源の節約になる。 | |
Person.prototype.outputName = function(){ | |
console.log(this.name); | |
} | |
//Person関数のプロトタイプに、aを定義し、 | |
//stringのaを代入する。 | |
Person.prototype.a = "a"; | |
//定義したコンストラクタ関数を使って、2つのオブジェクトを生成する。 | |
var person1 = new Person("Ted"); | |
var person2 = new Person("Barney"); | |
//prototypeに定義したoutputNameを呼び出す | |
person1.outputName(); //=>Ted | |
person2.outputName(); //=>Barney | |
//prototypeに定義したaプロパティを書き換えてみる。 | |
person1.a = "b"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment