Object.create
时间: 2023-09-01 08:13:52 浏览: 109
`Object.create()` 和 `new` 是 JavaScript 中创建对象的两种不同方式。
`Object.create()` 方法创建一个新对象,并将其原型关联到指定的对象。这个方法允许在不调用构造函数的情况下创建一个对象。
`new` 操作符创建一个新对象并将其关联到构造函数的原型。它还会调用构造函数,并将新创建的对象传递给构造函数的 `this` 变量。
总的来说,`Object.create()` 更多用于原型继承,而 `new` 更多用于构造函数继承。
相关问题
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(Book)和 Object.create(Book.prototype)有什么区别
Object.create(Book)和Object.create(Book.prototype)的区别在于创建的新对象的原型链不同。
当使用Object.create(Book)时,创建的新对象的原型是Book对象本身,它继承了Book对象的属性和方法。例如,如果Book对象有一个属性a,那么通过Object.create(Book)创建的新对象也会有属性a。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Object.create() 方法](https://blog.csdn.net/qq_43199014/article/details/126010399)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [Object.create()是怎样建立原型链的](https://blog.csdn.net/qzw752890913/article/details/105586523)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文