Object.create()
时间: 2023-09-04 14:08:40 浏览: 46
`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()` 方法创建的新对象的原型指向指定的对象,而不是指定对象本身。因此,如果在指定对象中修改某个属性或方法,新对象也会继承这些修改。
相关问题
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 中一个对象创建方法,它允许你创建一个新对象并指定该对象的原型。具体来说,它接收一个参数,该参数是新对象的原型,然后返回一个新对象,该对象的原型为传入的参数。
例如,下面的代码创建了一个 `person` 对象,然后使用 `Object.create()` 方法创建了一个新对象 `student`,并将 `person` 对象作为 `student` 的原型:
```
let person = {
name: 'John',
age: 30,
sayHello() {
console.log('Hello!');
}
};
let student = Object.create(person);
```
此时,`student` 对象继承了 `person` 对象的属性和方法,可以通过 `student` 对象访问它们:
```
console.log(student.name); // 'John'
console.log(student.age); // 30
student.sayHello(); // 'Hello!'
```
需要注意的是,如果你想给新对象 `student` 添加自己的属性或方法,可以直接在 `student` 对象上添加,而不会影响到 `person` 对象。例如:
```
student.major = 'Computer Science';
student.study = function() {
console.log('Studying...');
};
```
这样一来,`student` 对象就具有了自己的 `major` 属性和 `study()` 方法。