こんにちは、
JavaScriptとオブジェクト指向
JavaScriptはプロトタイプベースのオブジェクト指向プログラミング言語と言われています。new演算子を用いることで、
なお、
JavaScriptにおけるプロトタイプとnew
まずはごく簡単なプロトタイプとnew演算子のサンプルを見てみましょう。
function Point(x, y){
this.x = x;
this.y = y;
}
// var Point = function(){ /* */ };と書いてもよい
Point.prototype.length = function(){
return Math.sqrt(this.x * this.x + this.y * this.y);
};
var point1 = new Point(3, 4);
console.log(point1.length()); // 5
console.log(point1);
さらに、

この結果を見ると、
この__
なお、
さて、
まず関数
(Point) を定義し、 同時にPointがコンストラクタとなる 関数のprototypeにメソッド
(プロパティ) を追加定義し、 このメソッドが新しいオブジェクトに継承されるメソッドとなる 関数をnewで呼び出す
その関数(Point) のprototypeオブジェクトを__ proto__オブジェクトとする新しいオブジェクト (point1) が作られ、 そのオブジェクト (point1) をthisとして関数Pointが呼び出される
ここで大事なのは、
Point.prototype.distance = function(point){
if (!(point instanceof Point)) {
throw new Error('引数がPointのインスタンスでない');
}
var dx = this.x - point.x;
var dy = this.y - point.y;
return Math.sqrt(dx * dx + dy * dy);
};
var point2 = new Point(3, -4);
console.log(point1.distance(point2)); // 8
console.log(point1);

point1がnewで作られた後に、
なお上記コードではinstanceofでPointを継承した変数であるか調べています。このようにinstanceofで特定コンストラクタから作られたインスタンスであるか調べることができます。
ただし、
Point.prototype.distance = function(point){
var dx = this.x - point.x;
var dy = this.y - point.y;
return Math.sqrt(dx * dx + dy * dy);
};
console.log(point1.distance({x:3, y:-4})); // 8
どちらの方針がよいかは一概には言えませんが、
ネイティブオブジェクトのprototype
__
var array1 = [1, 2]; // new Array(1, 2)相当
console.log(array1.__proto__ === Array.prototype); // true
console.dir(array1);

配列array1はArrayコンストラクタのインスタンスであり、
Array.prototype.insert = function(v, i){
// i番目にvを挿入
this.splice(i, 0, v);
return this;
};
console.log(array1.insert(6, 1)); // [1, 6, 2]
このすべての配列に影響がでるというのは便利でもあり、
なお、
for (var p in array1) {
console.log(p, ':', array1[p]);
}
0 : 1 1 : 6 2 : 2 insert : function (v, i){ // i番目にvを挿入 this.splice(i, 0, v); return this; }
Array.
なお、
for (var p in point1) {
console.log(p, ':', point1[p]);
}
x : 3 y : 4 length : function (){ return Math.sqrt(this.x * this.x + this.y * this.y); } distance : function (point){ var dx = this.x - point.x; var dy = this.y - point.y; return Math.sqrt(dx * dx + dy * dy); }
こういったオブジェクト自身のプロパティか、
for (var p in array1) {
if (array1.hasOwnProperty(p)) {
console.log(p, ':', array1[p]);
}
}
for (var p in point1) {
if (point1.hasOwnProperty(p)) {
console.log(p, ':', point1[p]);
}
}
0 : 1 1 : 6 2 : 2 x : 3 y : 4
ただ、
また、
まとめ
今回はプロトタイプベースの継承と、