ES6 - Object.setPrototypeOf



藉助此函式,我們可以將指定物件的原型設定為另一個物件或 null。

語法

在此語法中,obj 是要設定其原型的物件,prototype 是物件的新原型(物件或 null)。

Object.setPrototypeOf(obj, prototype)

示例

<script>
   let emp = {name:'A',location:'Mumbai',basic:5000}
   let mgr = {name:'B'}
   console.log(emp.__proto__ == Object.prototype)
   console.log(mgr.__proto__ == Object.prototype)
   console.log(mgr.__proto__ ===emp.__proto__)
   Object.setPrototypeOf(mgr,emp)
   console.log(mgr.__proto__ == Object.prototype) //false
   console.log(mgr.__proto__ === emp)
   console.log(mgr.location,mgr.basic)

</script>

以上程式碼的輸出將如下所示 −

true
true
true
false
true
Mumbai 5000
廣告
© . All rights reserved.