JS原型鏈繼承

###介紹es6

function Parent(){
    this.name="Parent"
}
Parent.prototype.smoking=function(){
    console.log("抽菸")
}
let parent =new Parent()
console.log(parent.__proto__)//指向所屬類的原型
console.log(parent.__proto__.constructor)//指向當前所屬類的
console.log(parent.__proto__.__proto__) //指向Object
console.log(Parent.__proto__)//Function
console.log(Parent.__proto__.__proto__)//Object
複製代碼

繼承私有

function Parent(){
    this.name="Parent"
}

function Child(){
    this.age="18";
    Parent.call(this)
}
let child = new Child()
child.name;// "Parent"

複製代碼

繼承公有

function Parent(){
    this.name="Parent"
}
Parent.prototype.smoking=function(){
    console.log("抽菸")
}
function Child(){
    this.age="18"
}
Child.prototype.eat=function(){
    console.log("吃雪糕")
}
let child= new Child()
//一、將子類的原型的__proto__指向父類的 Prototype
Child.prototype.__proto__ = Parent.prototype
// 錯誤寫法 Child.prototype = Parent.prototype 不能是父親原型等於孩子原型  這樣孩子原型會被覆蓋 至關於不存在了 再取child.eat會報錯

//二、es6寫法
Child.prototype = Object.create(Parent.prototype,{constructor:{value:prototype}})
//3)、es7 
Object.setPrototypeof(Child.prototype,Parent.prototype)
複製代碼

ES6 繼承

class Parent{
    constructor(name){
        this.name =name
    }
    say(){
        console.log("say")
    }
}

class Child extends Parent{

}
let child = new Child("兒子")
console.log(child.name);// 兒子
child.say();// "say"
複製代碼
相關文章
相關標籤/搜索