JavaScript之各类继承方式和优缺点

JavaScript之各类继承方式和优缺点javascript

  1. 原型链继承
function Parson(){
    this.name = 'hy'
}
Parson.prototype.getName = function(){
    console.log(this.name)
}

function Child(){

}

Child.prototype = new Parson()

var Child1 = new Parson()

Child1.getName() // hy

问题:java

  1. 引用类型的属性被全部的实例共享,修改了会影响全部实例
function Parson(){
    this.name = 'hy'
    this.age = [13,15]
}
Parson.prototype.getName = function(){
    console.log(this.name)
}

function Child(){

}

Child.prototype = new Parson()

var Child1 = new Child()
Child1.age.push(16)
console.log(Child1.age) // [ 13, 15, 16 ]

var Child2 = new Child()
console.log(Child2.age) // [ 13, 15, 16 ]


Child1.getName() // hy
Child2.getName() // hy

    2. 在建立 Child 的实例时,不能向Parent传参函数

2.借用构造函数继承(经典继承)this

function Parson(){
    this.names = ['hy', 'ycl']
}

function Child(){
    Parson.call(this)
}

var child1 = new Child()

child1.names.push('zz')
console.log(child1.names) // [ 'hy', 'ycl', 'zz' ]

var child2 = new Child()
console.log(child2.names) // [ 'hy', 'ycl' ]

优势:spa

  1. 避免了引用类型的属性被全部实例共享
  2. 能够在Child中向Parson传参数
举个例子:
function Parson(name){
    this.names = name
}

function Child(name){
    Parson.call(this , name)
}

var child1 = new Child('hy')

console.log(child1.names) // hy

var child2 = new Child('ycl')
console.log(child2.names) // ycl

问题prototype

  1. 方法都在构造函数中定义,每次建立实例都会建立一遍方法。
相关文章
相关标签/搜索