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)文章
根據(jù)判斷瀏覽器類型屏幕分辨率自動調(diào)用不同CSS的代碼
根據(jù)判斷瀏覽器類型屏幕分辨率自動調(diào)用不同CSS的代碼...2007-02-02HTML5canvas 繪制一個圓環(huán)形的進度表示實例
這篇文章主要介紹了HTML5canvas繪制一個圓環(huán)形的進度表示實例的相關(guān)資料,需要的朋友可以參考下2016-12-12Javascript計算二維數(shù)組重復(fù)值示例代碼
這篇文章主要給大家介紹了利用Javascript計算二維數(shù)組重復(fù)值的方法,文中給出了詳細的示例代碼,相信對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。2016-12-12