Object.create()
方法使用给定对象的原型创建一个新对象。
示例
let Student = {
name: "Lisa",
age: 24,
marks: 78.9,
display() {
console.log("Name:", this.name);
}
};
// create object from Student prototype
let std1 = Object.create(Student);
std1.name = "Sheeran";
std1.display();
// Output: Name: Sheeran
create() 语法
create()
方法的语法是:
Object.create(proto, propertiesObject)
create()
方法是一个静态方法,通过 Object
类名进行调用。
create() 参数
create()
方法接受:
- proto - 应该作为新创建对象的原型的对象。
- propertiesObject (可选) - 一个对象,其可枚举的自有属性指定要添加到新创建对象的属性描述符。这些属性对应于 Object.defineProperties() 的第二个参数。
create() 返回值
- 返回一个具有指定原型对象和属性的新对象。
注意: 如果 proto 不是 null
或 Object
,则会抛出 TypeError
。
示例:使用 Object.create()
let Animal = {
isHuman: false,
sound: "Unspecified",
makeSound() {
console.log(this.sound);
},
};
// create object from Animal prototype
let snake = Object.create(Animal);
snake.makeSound(); // Unspecified
// properties can be created and overridden
snake.sound = "Hiss";
snake.makeSound(); // Hiss
// can also directly initialize object properties with second argument
let properties = {
isHuman: {
value: true,
},
name: {
value: "Jack",
enumerable: true,
writable: true,
},
introduce: {
value: function () {
console.log(`Hey! I am ${this.name}.`);
},
},
};
human = Object.create(Animal, properties);
human.introduce(); // Hey! I am Jack.
输出
Unspecified Hiss Hey! I am Jack.
另请阅读