Object.create用法


用法: Object.create(object, [,propertiesObject])

創建一個新對象,繼承object的屬性,可添加propertiesObject添加屬性,並對屬性作出詳細解釋(此詳細解釋類似於defineProperty第二個參數的結構)

var banana= {
    color: 'yellow',
    getColor: function(){
        return this.color
    }
}
//創建對象sub_banana
var sub_banana= Object.create(banana) console.log(sub_banana.color) //yellow console.log(sub_banana.getColor()) //yellow

添加propertiesObject

"use strict"
var banana= {
    color: 'yellow',
    getColor: function(){
        return this.color
    }
}
var sub_banana= Object.create(banana, {
  //添加taste屬性 taste: {
    //詳細解釋 writeable:
false, get: function(){ console.log('getTaste') return 'good' } },
  //添加weight
  weight: {
    value: 600
  } }) console.log(sub_banana.color) console.log(sub_banana.getColor()) console.log(sub_banana.taste) //good
console.log(sub_banana.weight) //600 sub_banana.taste
= 'bad' //報錯,writeable為false不可改變

此方法也常用於創建對象實例

function theSuper(_a){
    this.a= 100
}
theSuper.prototype.getA= function(){
    return this.a
}
//繼承prototype
var sub1= Object.create(theSuper.prototype)
//繼承prototype而不是構造函數內的值 console.log(sub1.a) //undefined sub1.a
= 100 console.log(sub1.getA()) //100

那么,此方法與new obj()的區別在哪?

Object.create的實現核心代碼:

Object.create =  function (o) {
    var F = function () {};
    F.prototype = o;
    return new F();
};

可見: 創建函數,將傳遞的對象賦給函數的prototype,再返回函數實例。

 

new obj()的核心實現代碼:

var o1 = new Object();
o1.[[Prototype]] = Base.prototype;
Base.call(o1);

創建對象,將被繼承對象的prototype賦給此對象,並且調用被繼承對象的方法來為其初始化。(因此new obj()不僅能繼承prototype,也能繼承構造函數內屬性)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM