欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中關(guān)于Object.create()的用法

 更新時間:2023年02月10日 14:30:44   作者:奮斗中的小余  
這篇文章主要介紹了JavaScript中關(guān)于Object.create()的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

JavaScript的Object.create()方法

ES5定義了一個名為Object.create()的方法,它創(chuàng)建一個對象,其中第一個參數(shù)就是這個對象的原型,Object.create()提供第二個可選參數(shù),用以對對象的屬性進行進一步描述。

// Object.create()是一個靜態(tài)方法
// 以下展示不同參數(shù)的用法

// 一個參數(shù)
var o = Object.create(null) // 相當于空對象,任何屬性都沒有
var o = Object.create(Object.prototype) // 相當于var o = {}
var o = Object.create({x: 1, y: 2}) // 相當于var o = {}; o.prototype = {x: 1, y: 2}

// 第二個參數(shù)是一個對象,用于給創(chuàng)建的對象添加屬性和屬性描述的
// 屬性又分為數(shù)據(jù)屬性和存取器屬性
// 數(shù)據(jù)屬性的描述符對象的屬性有value(值)、writable(可寫性)、enumerable(可枚舉性)、configurable(可配置性)
// 存取器屬性的描述符對象的屬性有g(shù)et(讀取)、set(寫入)、enumerable(可枚舉性)、configurable(可配置性)

// 兩個參數(shù)
var o = Object.create({x: 1, y: 2}, {
   a: {
   		value: 100,
   		......
   }
}) // 向創(chuàng)建的對象o添加一個數(shù)據(jù)屬性a,值為100,其它描述屬性默認為false

var o = Object.create({x: 1, y: 2}, {
   a: {
   		get() {
   			return this.x + this.y
   		},
   		......
   	}
}) // 向創(chuàng)建的對象o添加一個存取器屬性a,o.a時執(zhí)行其get方法,set屬性默認為undefined,其余描述屬性默認為false

JavaScript手寫Object.create函數(shù)

給大家分享一下手寫 Object.create 函數(shù)。

函數(shù)功能

Object.create()方法創(chuàng)建一個新對象,使用現(xiàn)有的對象來提供新創(chuàng)建的對象的__proto__

代碼:

function create(parentPrototype, props) {
? function Fn() {
?
? }
? Fn.prototype = parentPrototype;
? let fn = new Fn();
? for (let key in props) {
? ? Object.defineProperty(fn, key, {
? ? ? enumerable: true, // 如果不枚舉對象中無法查看到這個對象
? ? ? ...props[key]
? ? })
? }
? return fn
}
?
?
function Parent() {
? this.name = "parent";
}
?
Parent.prototype.eat = function () {
? console.log("eat");
};
?
function Child() {
? this.age = 9;
? Parent.call(this);
}
?
Child.prototype = create(Parent.prototype, { constructor: { value: Child } });
?
// { constructor: { value: Child } } ?這段代碼保證 Child 的 prototype 的 constructor 還指向 Child 的構(gòu)造函數(shù)
?
let child = new Child();
console.log(child.constructor,'constructor'); // [Function: Child] 'constructor'
child.eat() // eat

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論