js での extends の使用と原則

最初に、js の継承を特に包括的に説明している記事をお勧めします.その中の結論だけを取り上げ、
Javascript が今後どのように継承を実装するかを参照しますか?

1.継承の使い方

js でよく使われるのは extends で、使い方は次のとおりです。

class Father {
    
    
    constructor(name) {
    
    
      this.name = name
    }
    // 原型方法
    // 即 Person.prototype.getName = function() { }
    // 下面可以简写为 getName() {...}
    getName = function () {
    
    
      console.log('Person:', this.name)
    }
}

class child extends Father {
    
    
    constructor(name, age) {
    
    
        super(name)
        this.age = age
    }
    getAge = function () {
    
    
        console.log('Age:', this.age)
    }
}

const person = new child('Jim','28')
person.getName() // Person: Jim
person.getAge() // Age: 28

2. 継承の実装方法 - 寄生結合継承

継承を実現するには多くの方法があります。ここでは、それを示すために最適な方法を選択します。extendsこれは、使用される寄生結合方法でもあります。

function extend(father, child) {
    
    
    // 用 Object.create 拷贝父亲的prototype
    child.prototype = Object.create(father.prototype)
    //手动挂上构造器,指向自己的构造函数
    child.prototype.constructor = child
}

テストを受けます

// 测试例子
function father() {
    
    
    this.name = 'Tom';
    this.play = [1, 2, 3];
}
father.prototype.getName = function () {
    
    
    return this.name;
}

function child(friends) {
    
    
    father.call(this)
    this.friends = friends
} 

// 继承
extend(father,child)

child.prototype.getFriends = function () {
    
    
    return this.friends;
}

let person6 = new child('July');
console.log(person6.getName()); // Tom
console.log(person6.getFriends()); // July

おすすめ

転載: blog.csdn.net/baidu_33438652/article/details/124539505