object.create
时间: 2023-09-06 17:11:55 浏览: 101
Object.create() is a method in JavaScript that creates a new object with the specified prototype object and properties. It allows you to create a new object that inherits from an existing object, without the need to define a constructor function.
The syntax for Object.create() is:
```
Object.create(proto, [propertiesObject])
```
where `proto` is the prototype object to inherit from, and `propertiesObject` is an optional object that defines additional properties to be added to the newly created object.
Here's an example of using Object.create() to create a new object with a specific prototype:
```
const person = {
greeting: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const john = Object.create(person);
john.name = "John";
john.greeting(); // outputs "Hello, my name is John."
```
In this example, we create an object called `person` with a `greeting()` method. We then create a new object called `john` using `Object.create()`, and set its prototype to `person`. We then add a `name` property to `john`, and call the `greeting()` method, which accesses the `name` property using `this`.
阅读全文