JavaScript继承模式

2021-07-13  本文已影响0人  Lnevan

1,原型链继承

function Supper() {
  this.supper = 'supper'
}
Supper.prototype.showSupperProp = function () {
  console.log(this.supper)
}
function Sub() {
  this.sub = 'sub'
}
Sub.prototype = new Supper() //子类型的原型为父类型的一个实例对象
Supper.prototype.showSubProp = function () {
  console.log(this.sub)
}
let s = new Sub()
s.showSupperProp() //supper
console.log(s.constructor) //ƒ Supper() {
                            // this.supper = 'supper'
                            //}

为了让s的constructor指向的是Sub,应该要添加Sub.prototype.constructor = Sub

原型继承.png

2.借用构造函数继承(假的,实际上并没有继承)

function Person(name,age) {
  this.name = name
  this.age = age
}
function Student(name,age,sex) {
  Person.call(this,name,age) //相当于this.Person(name,age) 即 this.name = name;this.age = age
  this.sex = sex
}
let s = new Student('Tom',20,'男')
console.log(s.name,s.age,s.sex) //Tom 20 男

3.原型链+借用构造函数的组合继承

function Person(name,age) {
  this.name = name
  this.age = age
}
Person.prototype.setName = function(name) {
  this.name = name
}
function Student(name,age,sex) {
  Person.call(this,name,age) //为了得到属性,相当于this.Person(name,age) 即 this.name = name;this.age = age
  this.sex = sex
}
Student.prototype = new Person() //为了能看到父类型的方法
Student.prototype.constructor = Student //修正constructor属性
Student.prototype.setSex = function(sex) {
  this.sex = sex
}
let s = new Student('Tom',20,'男')
s.setSex('女')
s.setName('Amy')
console.log(s.name,s.age,s.sex) //Amy 20 女
上一篇 下一篇

猜你喜欢

热点阅读