js 继承

前段时间帮小学弟整理了一下 js 的继承

  • JS有哪些手段可以实现继承?
    1. 对象冒充
      • 在Child中创建临时变量this.flag 去接受 Parent  运行this.flag(参数) 实现继承 ---别忘了delete this.flag
    2. call()
      • 在Child中 使用Parent.call(this, arguments[i], ...) 
    3. apply()
      • 在Child中 使用Parent.call(this, [arguments[i] , .....]) 
    4. 原型
      • Child.prototype = new Parent()
    5. 混合式继承
      • 原型继承和call() 结合
  • 继承方式
    • 都是以上继承手段的自由组合
  • 我使用的构造函数的继承实现
function extend(A, B){
    var Temp= function(){}
    Temp.prototype = B.prototype
    A.prototype = new Temp()
    A.prototype.constructor = A
}
function Parent (a){
    this.name = a.name;
    this.sayHi = function(){
        console.log(this.name)
    }
 
}
function Child (a){
     Parent.call(this,a);
    this.age = a.age
}
 
extend(Child,Parent)
 
var a = new Child({name:"tdk",age:19})
 
原文地址:https://www.cnblogs.com/web-Rain/p/7323510.html