本文主要講3個問題
1.Object.defineProperties(obj, props)
2.Object.create(obj, [propertiesObject])
-
__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 源碼的時候自己做的一個知識擴展了。