js中的几种继承方法

在这之前先t讨论下js中的址传递和值传递:

值传递主要针对基本类型除null外 number undefined boolean string

址传递 :针对复杂的类型数据 object array date function

1.原型链继承 缺点:父实例与子实例共享了原型 方法 优点实现简单

function person(name){
  this.name=1
}
person.prototype.cc = [1,2,3]
function son(){
  this.age = 10
}
son.prototype = new person()
son.prototype.constructor = son 
var a = new son()
var b = new son()
a.cc[0] =88
console.log(a.cc, b.cc) // [88,1,2] [88,1,2]  

2.原型继承 缺点:不能够继承父自身属性    不能传递参数 共享问题 优点:实现简单

function person(name){
  this.name=1
}
person.prototype.cc = [1,2,3]
function son(){
  this.age = 10
}
son.prototype = person.prototype 
var a = new son()
var b = new son()
a.cc[0] =88
console.log(a.cc, b.cc) // [88,1,2] [88,1,2]  
console.log(a.name) // undefined

 3.apply call 方法实现继承  缺点:不能够继承父原型属性  优点:能传递参数 共享问题得到解决 不共享

function person(name){
  this.name=name
}
person.prototype.cc = [1,2,3]
function son(name,age){
  person.call(this,name)
  this.age = age
  
}
var a = new son(22,11)
var b = new son(33,44)
console.log(a.name) // 22

4.组合式继承 优点:能够传递参数,并且继承了父自身的方法 和原型上的方法  缺点:父实例和子实例共享了原型上的方法

function person(name){
  this.name=name
}
person.prototype.cc = [1,2,3]
function son(name,age){
  person.call(this,name)
  this.age = age
  
}
son.prototype = new person()
son.prototype.constructor = son
var a = new son("du",10)
var b = new son("xie",11)
a.cc[0] =88
console.log(a.cc, b.cc) // [88,1,2] [88,1,2]  
console.log(a.name, b.name) // du xie

5.组合式继承 + deepcopy 优点:能够传参数,无实例共享,继承了父原型上的方法和自身属性和方法 缺点:实现困难

function fu(name){
  this.name = name
}
fu.prototype.cc = [1,2,3]
function zi(name,age){
  fu.call(this,name)
  this.age = age
}
zi.prototype = deepcopy(fu.prototype)
var zi1 = new zi()
var zi2 = new zi()
zi1.cc[2] = 100
console.log(zi1.cc,zi2.cc)// [1,2,100] [1,2,3]


  function deepcopy(args){
    if(typeof args !== "object"){
      return args
    }
    if(args === null) return null
    if(args instanceof RegExp) return new RegExp(args)
    if(args instanceof Date) return new Date(args)
    let t = new args.constructor()
    for (let i in args){
      t[i] = deepcopy(args[i])
    }
    return t
}
//解决址传递的方法就是递归此属性 赋给另外一个地址 从而达到深拷贝的效果即共享问题

猜你喜欢

转载自blog.csdn.net/d649237053/article/details/90138144