对象原型
2025-02-17
原型链
原型的概念
JavaScript 中的每个对象都有一个内置的 prototype 属性,它指向该对象的原型对象。原型链是 JavaScript 实现继承的主要方式。
示例
// 创建一个简单对象
const myObject = {
city: "ShenZhen",
greet() {
console.log(`"Hello Welcome to ${this.city}"`);
}
}
myObject.greet();提示: 在浏览器控制台中输入对象名称后跟随一个点(如:
myObject.),会显示该对象所有可用的属性和方法。
属性遮蔽
概念
当一个对象的属性与其原型对象的属性同名时,对象自身的属性会"遮蔽"原型对象的同名属性。
示例
const animal = {
speak() {
console.log("动物发出声音");
}
};
const dog = Object.create(animal);
dog.speak = function() {
console.log("汪汪汪");
};
dog.speak(); // 输出: "汪汪汪"设置原型
JavaScript 提供了两种设置对象原型的方法:
- Object.create()
- 构造函数
Object.create()设置原型
Object.create() 方法创建一个新对象,使用现有对象作为新对象的原型:
const personPrototype = {
greet() {
console.log('Hello')
}
}
const carl = Object.create(personPrototype);
carl.greet()构造函数设置原型
| 概念 | 说明 |
|---|---|
| prototype 属性 | 所有函数都有的属性,指向原型对象 |
| proto | 对象实例指向其构造函数原型的内部链接 |
| 原型继承 | 通过原型链实现的对象继承机制 |
// 创建对象,有一个 greet() 方法
const personPrototype = {
greet() {
console.log(`Hello ${this.name}`)
}
}
// 构造函数
function Person(name) {
this.name = name
}
// 使用 Object.assign 将 personPrototype 中定义的方法绑定到 Person 函数的 prototype 属性上
Object.assign(Person.prototype, personPrototype)
// 创建实例
const shenzhen = new Person('ShenZhen')
shenzhen.greet()自由属性
自由属性(Own Properties)是直接定义在对象上的属性,而不是从原型链继承的属性。
检查自由属性
function Person(name) {
this.name = name
}
const irma = new Person('Irma')
// 检查属性是否是自由属性
console.log(Object.hasOwn(irma, 'name'))
console.log(Object.hasOwn(irma, 'greet'))参考: MDN-对象原型