(前端手撕)7. 手写继承的几种方法
手写继承的几种方法
1. 原型链继承
//父类型 function Person(name, age) { this.name = name, this.age = age, this.play = [1, 2, 3] this.setName = function () { } } // Person.prototype.setAge = function () { } //子类型 function Student(price) { this.price = price this.setScore = function () { } } Student.prototype = new Person('wang',23) // 子类型的原型为父类型的一个实例对象 var s1 = new Student(15000) var s2 = new Student(14000) // console.log(s1.setAge) console.dir(s1,s2)
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
2. 借用构造函数继承
function Person(name, age) { this.name = name, this.age = age, this.setName = function () {} } Person.prototype.setAge = function () {} function Student(name, age, price) { Person.call(this, name, age) // 相当于: this.Person(name, age) /*this.name = name this.age = age*/ this.price = price } var s1 = new Student('Tom', 20, 15000) console.log(s1);
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
3. 原型链+借用构造函数的组合继承
function Person(name, age) { this.name = name, this.age = age, this.setAge = function () { } } Person.prototype.setAge = function () { console.log("111") } function Student(name, age, price) { Person.call(this,name,age) this.price = price this.setScore = function () { } } Student.prototype = new Person() Student.prototype.constructor = Student//组合继承也是需要修复构造函数指向的 var s1 = new Student('Tom', 20, 15000) var s2 = new Student('Jack', 22, 14000) console.log(s1)
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
4. ES6中class 的继承
class Person { //调用类的构造方法 constructor(name, age) { this.name = name this.age = age } //定义一般的方法 showName() { console.log("调用父类的方法") console.log(this.name, this.age); } } let p1 = new Person('kobe', 39) console.log(p1) //定义一个子类 class Student extends Person { constructor(name, age, salary) { super(name, age)//通过super调用父类的构造方法 this.salary = salary } showName() {//在子类自身定义方法 console.log("调用子类的方法") console.log(this.name, this.age, this.salary); } } let s1 = new Student('wade', 38, 1000000000) console.log(s1) s1.showName()