javascript原型链的继承

引言

javascript(以下简称js)是面向对象编程的语言吗?No,No,No。何为对象,说到这里估计有的朋友已经在开车了(这里是去幼儿园的车,请不要紧张)。所谓对象即封装、继承、多态。那js中的面向对象从何而来,这是一个值得思考的问题。现在我以浅显的认知带大家去解读js中的原型,以下知识点包含构造函数的继承、原型链的继承、组合继承。

  • 准备工作,创建两个构造函数

// 父构造函数
function Parent (name) {
    this.name = name
    this.color = ['red', 'black']
}

Parent.prototype.sayName = function () {
    console.log(this.name)
}

// 子构造函数
function Child () {

}

1.构造函数的继承

  • 从以下的代码运行结果看,只有最后一段代码输出不是我们想要看到的。所以,我们可以总结出......(算了,我还是说了吧!),这种继承方式继承不了原型上的东西,因此出现第二种原型链的继承方式,请您往下看。
// 父构造函数
function Parent (name) {
    this.name = name
    this.colors = ['red', 'black']
}

Parent.prototype.sayName = function () {
    console.log(this.name)
}

// 子构造函数
function Child () {
    Parent.call(this, 'zs') //方式一 继承Parent的属性
    // Parent.apply(this, ['zs']) // 方式二 继承Parent的属性
}

let child1 = new Child()
let child2 = new Child()
child1.colors.push('white')
console.log(child1.colors) //['red', 'black', 'white']
console.log(child2.colors) //['red', 'black']
console.log(Parent.prototype.constructor.name) //Parent
console.log(Child.prototype.constructor.name) //Child
console.log(child1.name) //zs
child1.sayName() //报错,说sayName不是一个函数

2.原型链的继承

  • 运行结果出现了两个出人意料的地方。
  • 1.colors同时改变了,很显然这不是我们想要的(别急,稳住)
  • 2.Child构造函数指向Parent(这指向就有点混乱了)
  • 3.思考一下吧!
// 父构造函数
function Parent (name) {
    this.name = name
    this.colors = ['red', 'black']
}

Parent.prototype.sayName = function () {
    console.log(this.name)
}

// 子构造函数
function Child () {
    //Parent.call(this, 'zs') //方式一 继承Parent的属性
    // Parent.apply(this, ['zs']) // 方式二 继承Parent的属性
}

Child.prototype = new Parent('ls') //继承了Parent的实例
let child1 = new Child()
let child2 = new Child()
child1.colors.push('white')
console.log(child1.colors) //['red', 'black', 'white']
console.log(child2.colors) //['red', 'black',, 'white']
console.log(Parent.prototype.constructor.name) //Parent
console.log(Child.prototype.constructor.name) //Parent
console.log(child1.name) //ls
child1.sayName() //ls

3.组合继承

  • 原谅我,写着文档让别人看太难了。朋友们自己去理解吧,实在不解的地方再私信吧!
  • 还是简单说下吧!组合继承听这名字应该就很好懂,构造函数继承和原型链继承的组合体。
// 父构造函数
function Parent (name) {
    this.name = name
    this.colors = ['red', 'black']
}

Parent.prototype.sayName = function () {
    console.log(this.name)
}

// 子构造函数
function Child () {
    Parent.call(this, 'zs') //方式一 继承Parent的属性
    // Parent.apply(this, ['zs']) // 方式二 继承Parent的属性
}

Child.prototype = Object.create(Parent.prototype, { constructor: { value: Child } }) //方式一
// Child.prototype = { ...Parent.prototype, constructor: Child } //方式二
let child1 = new Child()
let child2 = new Child()
child1.colors.push('white')
console.log(child1.colors) //['red', 'black', 'white']
console.log(child2.colors) //['red', 'black']
console.log(Parent.prototype.constructor.name) //Parent
console.log(Child.prototype.constructor.name) //Child
console.log(child1.name) //zs
child1.sayName() //zs
发布了8 篇原创文章 · 获赞 6 · 访问量 2565

猜你喜欢

转载自blog.csdn.net/qq_40344815/article/details/103957413