标签:proto 对象 create Object new 方法 propertiesObject
Object.create()方法的实现
Object.create()方法用于创建一个新对象并将这个新对象的[[Prototype]]设置为特定的对象。另外,Object.create()方法还有一个可选的参数propertiesObject,这个参数类似于Object.defineProperties()方法的第二个参数,指定了将要添加到新对象中的属性和属性的各个特性。在实现Object.create()方法时要注意确保第一个参数是非空的对象。另外,如果第二个参数不是undefined,同样要确保它是非空的对象。
1 const myObjectCreate = function (proto, propertiesObject) { 2 if (typeof proto !== "object" && typeof proto !== "function") { 3 throw new TypeError("The prototype must be a object"); 4 } else if (proto === null) { 5 throw new TypeError("The prototype cannot be null"); 6 } 7 8 // 创建构造函数,并将构造函数的原型对象设置为proto 9 const F = function () {}; 10 F.prototype = proto; 11 12 // 创建新对象 13 let obj = new F(); 14 15 if (propertiesObject && typeof propertiesObject === "object") { 16 Object.defineProperties(obj, propertiesObject); 17 } 18 19 return obj; 20 } 21 22 let person = myObjectCreate({name : "Alex"}, { 23 age : { 24 writable : false, 25 enumerable : true, 26 value : 18 27 } 28 }); 29 console.log(person.name, person.age); // Alex 18
标签:proto,对象,create,Object,new,方法,propertiesObject 来源: https://www.cnblogs.com/ccpeng/p/14715480.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。