在JavaScript中,原型链是对象继承属性的主要方式。每个对象都有一个指向其原型(prototype)的内部链接。当试图访问一个对象的属性时,如果该对象本身没有这个属性,那么JavaScript会查看该对象的原型对象是否有这个属性。这个过程会一直持续到原型链的末端,即Object.prototype
。如果仍然找不到该属性,那么就会返回undefined
。
下面是一个详细的示例,展示了如何在JavaScript中创建和使用原型链:
javascript复制代码
// 创建一个基础对象(原型) |
|
function Animal(name) { |
|
this.name = name; |
|
this.sleep = function() { |
|
console.log(this.name + ' is sleeping.'); |
|
}; |
|
} |
|
// 创建一个方法,添加到Animal的原型上 |
|
Animal.prototype.eat = function() { |
|
console.log(this.name + ' is eating.'); |
|
}; |
|
// 创建一个继承自Animal的Dog对象 |
|
function Dog(name, breed) { |
|
// 调用Animal的构造函数,设置Dog的name属性 |
|
Animal.call(this, name); |
|
this.breed = breed; |
|
this.bark = function() { |
|
console.log(this.name + ' is barking.'); |
|
}; |
|
} |
|
// 设置Dog的原型为新的Animal对象 |
|
Dog.prototype = Object.create(Animal.prototype); |
|
// 修复constructor属性,因为Object.create()会创建一个新的对象,其constructor属性默认指向Object |
|
Dog.prototype.constructor = Dog; |
|
// 创建一个Dog对象 |
|
var d = new Dog('Mitzie', 'Chihuahua'); |
|
// 测试原型链上的属性 |
|
d.eat(); // 调用Animal原型上的方法 |
|
d.bark(); // 调用Dog对象自身的方法 |
|
d.sleep(); // 调用Dog对象从Animal继承的方法 |
|
// 输出: |
|
// Mitzie is eating. |
|
// Mitzie is barking. |
|
// Mitzie is sleeping. |
在这个例子中,Dog
对象继承自Animal
对象。我们创建了一个Dog
的原型对象,并将其设置为一个新的Animal
对象(通过Object.create(Animal.prototype)
)。然后,我们修复了Dog.prototype.constructor
,因为Object.create()
会创建一个新的对象,其constructor
属性默认指向Object
。
当我们创建一个Dog
实例(如d
)时,我们可以访问定义在Dog
上的属性(如bark
),以及通过原型链从Animal
继承的属性(如eat
和sleep
)。