JavaScript Object.create()

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 不是 nullObject,则会抛出 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.

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战