前端 · 2 分钟阅读
对象原型
目录
原型链
原型的概念
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')) // true
console.log(Object.hasOwn(irma, 'greet')) // false
参考:MDN - 对象原型