Object.create()重写解读
时间: 2023-03-26 14:01:47 浏览: 69
Object.create() 是 JavaScript 中的一个方法,用于创建一个新对象,新对象的原型链指向传入的参数对象。具体来说,它会返回一个新对象,这个新对象的原型链指向传入的参数对象,同时可以传入一个可选的属性描述对象,用于定义新对象的属性。这个方法可以用于实现对象的继承,也可以用于创建一个纯净的对象,不继承任何属性和方法。
相关问题
object.create
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`.
Object.create()
`Object.create()` 是一个JavaScript方法,它创建一个新对象,并将指定的对象作为新对象的原型。这个方法可以用来实现基于原型的继承。
具体来说,`Object.create()` 方法接收一个参数,即用作新对象原型的对象。例如:
```
const person = {
greet() {
console.log('Hello!');
}
};
const john = Object.create(person);
john.greet(); // 输出 "Hello!"
```
在上面的例子中,我们先定义了一个 `person` 对象,它有一个 `greet` 方法。然后,我们使用 `Object.create()` 方法以 `person` 为原型创建了一个新对象 `john`,并调用了 `john` 的 `greet` 方法。
需要注意的是,`Object.create()` 方法创建的新对象的原型指向指定的对象,而不是指定对象本身。因此,如果在指定对象中修改某个属性或方法,新对象也会继承这些修改。