プロトタイプチェーンの継承:
利点: 親クラスのメソッドを再利用できる
欠点: 親クラスのすべての参照型 (配列オブジェクト) がサブクラスで共有されるため、1 つのサブクラスのデータが変更されると、他のデータも影響を受けます。
function Person() {
this.name = '张三';
this.eats = ['香蕉', '苹果'];
this.getName = function () {
console.log(this.name);
}
}
Person.prototype.get = function () {
console.log('Person 继承的方法');
}
function Student() {
}
Student.prototype = new Person
console.log('------------------p1---------------');
const p1 = new Student()
p1.get()
p1.eats.push('橘子') // p1 更改了 eats 数组里面的值 ,p2 拿到的就是更改之后的值
p1.name = '李四' // 更改 name 值 ,p2 不受影响
console.log(p1.name);
console.log(p1.eats);
console.log('-----------------p2----------------');
const p2 = new Student()
console.log(p2.name);
console.log(p2.eats);
p2.get()
コンストラクターの継承
利点: 親クラスのアプリケーション タイプはサブクラスによって変更されず、相互に影響を与えません。
欠点: サブクラスは、親クラスのプロトタイプ プロパティのメソッドとパラメーターにアクセスできません。
function Person() {
this.name = '张三';
this.eats = ['香蕉', '苹果'];
this.getName = function () {
console.log(this.name);
}
}
Person.prototype.get = () => { // 此方法不能使用
console.log('Person 继承的方法');
}
function Student() {
Person.call(this) // 指向 Student
}
console.log('-----------------p1----------------');
const p1 = new Student()
p1.name = 'ssss'
p1.eats.push('菠萝') // 只会自己更改,不会影响别人
console.log(p1);
console.log('-----------------p2----------------');
const p2 = new Student()
console.log(p2);
このとき、存在しないgetメソッドを出力します。
構成の継承
利点: 1. 親クラスを再利用できる
2. 親クラスのコンストラクターの参照プロパティは共有されません。
欠点: 親クラスのコンストラクターが 2 回呼び出され、同じ属性とメソッドのコピーが 2 つ存在するため、パフォーマンスに影響します。
function Person() {
this.name = '张三';
this.eats = ['香蕉', '苹果'];
this.getName = function () {
console.log(this.name);
}
}
Person.prototype.get = () => {
console.log('Person 继承的方法');
}
function Student() {
Person.call(this)
}
Student.prototype = new Person // 增
const p1 = new Student()
console.log(p1);
寄生組成の継承
function Person() {
this.name = '张三';
this.eats = ['香蕉', '苹果'];
this.getName = function () {
console.log(this.name);
}
}
Person.prototype.get = () => {
console.log('Person 继承的方法');
}
function Student() {
Person.call(this)
}
// 创建一个中转站
const Fn = function () { }
Fn.prototype = Person.prototype
Student.prototype = new Fn() // 增
const p1 = new Student
p1.get()
console.log(p1);