Object.create()和setPrototypeof和Child.prototype = Parent.prototype和Child.prototype = new Parent()的區別
阿新 • • 發佈:2020-12-10
## 1、Child.prototype = new Parent()取不到Child原型上的屬性,constructor指向Parent //父類 function Parent(){ this.name = "P_Name"; } Parent.prototype.func=function(){ console.log("Parent Func"); } //子類 function Child(){ } Child.prototype=newParent(); Child.prototype.func = function(){ console.log("Child Func"); } var child = new Child; var parent = new Parent; child.func();//Child Func console.log(child.name);//P_Name console.log(Child.prototype.constructor) // Parent parent.func();//Parent Func ## 2、Child.prototype = Parent.prototype取不到Parent的建構函式屬性,constructor指向Parent,而且對子類的原型方法重寫會使父類的原型方法被重寫function Child2(){ } # 以下賦值將覆蓋Parent.prototype.func方法 Child2.prototype=Parent.prototype; Child2.prototype.func = function(){ console.log("Child2 Func"); } var child2 = new Child2; child2.func();//Child2 Func console.log(child2.name);//undefined console.log(Child2.prototype.constructor) // Parent parent.func();//Child2 Func
setPrototypeOf 與 Object.create區別
可以用prototype訪問的只有function型別,其他型別只能用getPrototypeOf或者proto,其他型別也都是通過function生成的(String,Number……涉及到隱式建立物件)
物件的原型只是一個引用,指向另外一個物件。物件原型之間的巢狀組成了原型鏈,原型鏈的作用是維護訪問物件屬性的查詢,確定訪問許可權。
若存在A和B倆個函式,讓A的原型指向B
1.setPrortotypeOf
Object.setPrototypeOf(A.prototype,B.prototype)
2.Create
A.prototype = Object.create(B.prototype)
倆者都可以達到設定物件原型的功能,但是具體表現上有一些區別。
程式碼如下
function Animal (name,sound) { this.name = name this.sound = sound } Animal.prototype.shout = function () { console.log(this.name + this.sound) } let dog = new Animal('pipi','wang!wang!') // 定義Plants function Plants (name) { this.name = name this.sound = null } // 函式接收引數用於區分 Plants.prototype.shout = function (xssss) { console.log(this.name + this.sound +'plants tag') } Plants.prototype.genO2 = function () { console.log(this.name + '生成氧氣。') }
Animal.prototype = Object.create(Plants.prototype) console.log(Animal.prototype) /* Plants {} __proto__: shout: ƒ (xssss) genO2: ƒ () constructor: ƒ Plants() __proto__: Object */ let cat = new Animal('mimi','miao~miao~') dog.shout() // pipi wang!wang! cat.shout() // mimi miao~miao~ plants tag cat.genO2() // mimi 生成氧氣。
使用setPrototypeOf
Object.setPrototypeOf(Animal.prototype,Plants.prototype) console.log(Animal.prototype) /* Plants {shout: ƒ, constructor: ƒ} shout: ƒ (xssss) constructor: ƒ Animal(name,sound) __proto__: shout: ƒ () genO2: ƒ () constructor: ƒ Plants() __proto__: Object */ dog.shout() // pipi wang!wang! cat.shout() // mimi miao~miao~ cat.genO2() // mimi 生成氧氣。
總結
使用Object.create,Animal.prototype將會指向一個空物件,空物件的原型屬性指向Plants的prototytpe。所以我們不能再訪問Animal的原有prototypoe中的屬性。Object.create的使用方式也凸顯了直接重新賦值。
使用Object.setPrototypeOf則會將Animal.prototype將會指向Animal原有的prototype,然後這個prototype的prototype再指向Plants的prototytpe。所以我們優先訪問的Animal,然後再是plants。
在進行倆個原型之間的委託時使用setPrototype更好,Object.create更適和直接對一個無原生原型的物件快速進行委託。