Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的proto。
语法:Object.create(proto, [propertiesObject])
- proto:新创建对象的原型对象。必填
- propertiesObject:可选。若没有指定为undefined,则是要添加到新创建对象的可枚举属性(自身定义的属性,而不是原型链上的枚举属性。这些属性对应Object.defineProperties()的第二个参数 。
propertiesObject 参数的详细解释:(默认都为false)
数据属性:
-
writable: 是否可任意写
-
configurable:是否能够删除,是否能够被修改
-
enumerable:是否能用 for in 枚举
-
value:值
访问属性:
- get()访问
- set()设置
返回值:一个新对象,带着指定的原型对象和属性。
const person = {
isable:false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
}
var onePerson = Object.create(person); // onePerson继承person对象
onePerson.__proto__ === person; // true

const person = {
isable:false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
}
var onePerson = Object.create(person,{
color:{ writable: true, configurable:true, value: 'red' },
bar: {
configurable: false,
get: function() { return 10; },
set: function(value) {
console.log("Setting `o.bar` to", value);
}
}
});

本文详细解析了JavaScript中Object.create()方法的使用,包括其语法、参数和返回值。通过实例展示了如何创建新对象并指定原型对象,以及如何定义新对象的属性。
829

被折叠的 条评论
为什么被折叠?



