この記事では、JavaScriptプロトタイプチェーン継承の使用法を分析します。参照のためにそれを共有してください。特定の分析は次のとおりです。
次のようにコードをコピーします:function shape(){
this.name = 'shape';
this.toString = function(){
this.nameを返します。
}
}
function twodshape(){
this.name = '2d shape';
}
関数三角形(側、高さ){
this.name = 'triangle';
this.side = side;
this.height = height;
this.getarea = function(){
this.side*this.height/2を返します。
};
}
/* 継承 */
twodshape.prototype = new Shape();
triangle.prototype = new Twodshape();
オブジェクトのプロトタイププロパティを完全に書き換えると、オブジェクトのコンストラクタープロパティに特定のマイナスの影響を与えることがあります。
したがって、関連する継承関係の設定を完了した後、これらのオブジェクトのconst属性をそれに応じてリセットすることは非常に良い習慣です。以下に示すように:
コードコピーは次のとおりです。Twodshape.prototype.constructor= twodshape;
triangle.prototype.constructor = triangle;
リライト:
コードを次のようにコピーします:function shape(){}
shape.prototype.name = 'shape';
shape.prototype.tostring = function(){
this.nameを返します。
}
function twodshape(){}
twodshape.prototype = new Shape();
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name = '2d shape';
関数三角形(側、高さ){
this.side = side;
this.height = height;
}
triangle.prototype = new Twodshape;
triangle.prototype.constructor = triangle;
triangle.prototype.name = 'triangle';
triangle.prototype.getarea = function(){
this.side*this.height/2を返します。
}
もう一度書き直します(バリューパスの代わりに参照パス):
コードを次のようにコピーします:function shape(){}
shape.prototype.name = 'shape';
shape.prototype.tostring = function(){
this.nameを返します。
}
function twodshape(){}
twodshape.prototype = shape.prototype;
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name = '2d shape';
関数三角形(側、高さ){
this.side = side;
this.height = height;
}
triangle.prototype = twodshape.prototype;
triangle.prototype.constructor = triangle;
triangle.prototype.name = 'triangle';
triangle.prototype.getarea = function(){
this.side*this.height/2を返します。
}
効率は改善されていますが、このような方法には副作用があります。これは、値の合格ではなく参照が通過するため、「親オブジェクト」の名前値が影響を受けるためです。
子オブジェクトと親オブジェクトは同じオブジェクトを指します。したがって、子オブジェクトがプロトタイプを変更すると、親オブジェクトもすぐに変更されます。
もう一度書き直します(一時的なコンストラクターを使用):
コードを次のようにコピーします:function shape(){}
shape.prototype.name = 'shape';
shape.prototype.tostring = function(){
this.nameを返します。
}
function twodshape(){}
var f = function(){}
f.prototype = shape.prototype;
twodshape.prototype = new f();
twodshape.prototype.constructor = twodshape;
twodshape.prototype.name = '2d shape';
関数三角形(側、高さ){
this.side = side;
this.height = height;
}
f.prototype = twodshape.prototype;
triangle.prototype = new f();
triangle.prototype.constructor = triangle;
triangle.prototype.name = 'triangle';
triangle.prototype.getarea = function(){
this.side*this.height/2を返します。
}
効率は改善されていますが、このような方法には副作用があります。これは、値の合格ではなく参照が通過するため、「親オブジェクト」の名前値が影響を受けるためです。
子オブジェクトと親オブジェクトは同じオブジェクトを指します。したがって、子オブジェクトがプロトタイプを整列して変更すると、親オブジェクトもすぐに変更されます。
この記事がみんなのJavaScriptプログラミングに役立つことを願っています。