JavaScript Object相關(guān)

本文主要講3個問題
1.Object.defineProperties(obj, props)
2.Object.create(obj, [propertiesObject])

  1. __proto__prototype理解
1. Object.defineProperties(obj, props)

功能: 方法直接在一個對象上定義一個或多個新的屬性或修改現(xiàn)有屬性,并返回該對象。
obj: 將要被添加屬性或修改屬性的對象
props: 該對象的一個或多個鍵值對定義了將要為對象添加或修改的屬性的具體配置

// 例子如下:
var VNode = function VNode (
  tag,
  data,
  children,
  text,
  elm,
  context,
  componentOptions,
  asyncFactory
) {
  this.tag = tag;
  this.data = data;
  this.children = children;
  this.text = text;
  this.elm = elm;
  // ...(省略部分代碼)
};

var prototypeAccessors = { child: { configurable: true } };

// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
  return this.componentInstance
};

Object.defineProperties( VNode.prototype, prototypeAccessors );
2. Object.create(obj, [propertiesObject])

功能:創(chuàng)建一個新對象,使用現(xiàn)有的對象來提供新創(chuàng)建的對象的__proto__。
obj: 一個對象,應(yīng)該是新創(chuàng)建的對象的原型。
propertiesObject:可選。該對象的一個或多個鍵值對定義了將要為對象添加或修改的屬性的具體配置

  • Object.create(null)b創(chuàng)建了一個空對象,在該對象上沒有繼承 Object.prototype 原型鏈上的屬性或者方法。

    空對象屬性.png

  • 以字面量創(chuàng)建空對象:var o = {}; 相當(dāng)于 var o = Object.create(Object.prototype);

    image.png

  • 使用Object.create()是將對象繼承到__proto__屬性上

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};
const me = Object.create(person);
me.name = ‘Matthew’; // ‘name’ 是 ‘me’ 的屬性,不存在于‘person’上
me.isHuman = true; // 繼承的屬性可以重寫(覆蓋)

對象打印后展開如下:
image.png
// 例子如下
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);

3. __proto__prototype理解

在JS里,萬物皆對象。方法(Function)是對象,方法的原型(Function.prototype)是對象。因此,它們都具有屬性__proto__,可稱為隱式原型,一個對象的隱式原型指向構(gòu)造該對象的構(gòu)造函數(shù)的原型,這也保證了實例能夠訪問在構(gòu)造函數(shù)原型中定義的屬性和方法。

  • __proto__是JavaScript里的原型
  • prototype是在 function 中特有的原型屬性 。function 的原型屬性指向一個Object,并且Object的constructor屬性指向了這個構(gòu)造函數(shù)本身。

·
·
·
以上就是閱讀vue.js 源碼的時候自己做的一個知識擴展了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容