// 定义Parent构造函数
function Parent() {
// Parent的属性
this.value = 'parent value';
// Parent的方法
this.getInfo = function() {
return `Value from Parent: ${this.value}`;
};
}
// 定义Child构造函数并继承自Parent
function Child() {
// 调用Parent构造函数,确保Child实例能继承到Parent的属性
Parent.call(this);
// Child自身的属性
this.childValue = 'child value';
}
// 设置Child的原型为Parent的实例,实现继承
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// Child的实例方法
Child.prototype.getChildInfo = function() {
// 以安全且高效的方式调用Parent的方法,并确保this指向正确
const parentInfo = Parent.prototype.getInfo.call(this);
return `${parentInfo}, and Child value: ${this.childValue}`;
};
// 创建Child的实例
const child = new Child();
console.log(child.getChildInfo());
// 严格模式下的情况
// 在严格模式下,如果没有正确处理this的指向,直接调用Parent的方法可能会导致this为undefined
// 例如,以下代码在严格模式下会报错
// function Child() {
// 'use strict';
// // 没有正确设置this指向,直接调用Parent的方法会出错
// const badCall = Parent.prototype.getInfo();
// // Uncaught TypeError: Cannot read property 'value' of undefined
// }
代码解释
- Parent构造函数:定义了
value
属性和getInfo
方法,getInfo
方法使用了this
来访问value
属性。
- Child构造函数:通过
Parent.call(this)
调用Parent
构造函数,将Parent
的属性和方法绑定到Child
的实例上,确保Child
实例能继承到Parent
的属性。
- 设置原型链:
Child.prototype = Object.create(Parent.prototype)
将Child
的原型设置为Parent
原型的实例,从而实现继承。同时,Child.prototype.constructor = Child
确保Child
实例的constructor
属性指向Child
构造函数。
- Child的实例方法:
getChildInfo
方法中,通过Parent.prototype.getInfo.call(this)
以安全的方式调用Parent
的getInfo
方法,并将this
正确指向Child
的实例,这样getInfo
方法就能正确访问Child
实例的属性。
- 严格模式下的问题:在严格模式下,如果没有正确设置
this
的指向,直接调用Parent
的方法(如Parent.prototype.getInfo()
)会导致this
为undefined
,因为严格模式下不会自动将全局对象作为this
的默认值,从而引发错误。所以在严格模式下,必须使用call
、apply
或bind
等方法来正确设置this
的指向。