0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点#Object.create的使用

Hyggelook 2022-02-11 阅读 42

在查看某框架的源码时,发现有大量使用了Object.create方法,例如

#yyds干货盘点#Object.create的使用_Object.create

#yyds干货盘点#Object.create的使用_Object.create_02

现参考看mdn出浅的总结一下

1.语法

/**
* Object.create(proto,[propertiesObject])
* 方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
* proto: 新创建对象的原型对象
* propertiesObject: 可选。需要传入一个对象,
该对象的属性类型参照Object.defineProperties()的第二个参数。
如果该参数被指定且不为 undefined,该传入对象的自有可枚举属性(即其自身定义的属性,
而不是其原型链上的枚举属性)将为新创建的对象添加指定的属性值和对应的属性描述符。
* 返回值: 一个新对象,带着指定的原型对象和属性。
*/

2.代码

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" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

console.log('me', me)

#yyds干货盘点#Object.create的使用_Object.create_03

就近访问原则

3.核心代码说明

#yyds干货盘点#Object.create的使用_Object.create_04

console.log('me.__proto__', me.__proto__)
console.log('aa', me.__proto__ === person) // true

#yyds干货盘点#Object.create的使用_Object.create_05

也就是将参数赋值给新创建对象的__proto__

4.总结

  • 第一个参数为新创建对象(也就是返回对象的原型对象)
举报

相关推荐

0 条评论