构造函数窃取(constructor stealing)是 javascript 中实现继承的一种经典模式,其核心做法是在子类的构造函数内部调用父类的构造函数。具体而言,通过 call、apply 或 bind 方法,将父类构造函数的执行上下文(this)绑定到子类的新实例上,从而让子类实例拥有父类定义的实例属性。这样做的好处是每个子类实例都拥有独立的属性副本,避免了引用类型属性的共享问题,但缺点是父类原型上的方法无法被继承。

构造函数窃取如何避免引用类型共享?
构造函数窃取通过为每个子类实例独立执行父类构造函数来解决引用类型共享问题。在传统的原型链继承中,如果父类原型包含数组或对象等引用类型属性,所有子类实例都会共享同一个引用,导致修改一个实例的属性会影响其他实例。而使用构造函数窃取时,父类构造函数在子类构造函数内部被调用,每次创建子类实例时都会重新执行父类构造函数,从而为每个实例分配全新的引用类型属性副本。

function Parent(name) {
this.name = name;
this.colors = ["red", "blue"];
}
function Child(name, age) {
// 窃取构造函数:调用 Parent 构造函数,this 指向 Child 实例
Parent.call(this, name);
this.age = age;
}
const child1 = new Child("Alice", 10);
const child2 = new Child("Bob", 12);
child1.colors.push("green");
console.log(child1.colors); // ["red", "blue", "green"]
console.log(child2.colors); // ["red", "blue"] - 不受影响
上述代码展示了构造函数窃取的典型用法。在 Child 构造函数中,通过 Parent.call(this, name) 调用父类构造函数,将 this 绑定到当前 Child 实例。这样,child1 和 child2 各自拥有独立的 colors 数组。当 child1 修改自己的 colors 时,child2 的 colors 保持不变,证明了引用类型属性没有被共享。
构造函数窃取与原型链结合如何解决方法继承问题?
单独使用构造函数窃取无法继承父类原型上的方法,因此需要结合原型链继承来实现完整的继承机制。具体做法是将子类的原型设置为父类的一个实例,这样子类实例就可以访问父类原型上的方法。同时,为了保持构造函数属性的正确性,还需要手动设置子类的 constructor 属性。这种组合方式既解决了引用类型共享问题,又实现了方法的继承。

function Parent(name) {
this.name = name;
this.colors = ["red", "blue"];
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, age) {
// 窃取构造函数
Parent.call(this, name);
this.age = age;
}
// 原型链继承:将 Child 原型设置为 Parent 的实例
Child.prototype = new Parent();
// 修复 constructor 属性
Child.prototype.constructor = Child;
const child = new Child("Alice", 10);
console.log(child.getName()); // "Alice"
console.log(child.colors); // ["red", "blue"]
在上述代码中,首先通过 Parent.call(this, name) 窃取构造函数,确保每个 Child 实例拥有独立的 name 和 colors 属性。然后,通过将 Child.prototype 设置为 new Parent(),使得 Child 实例可以访问 Parent.prototype 上的 getName 方法。最后,手动设置 Child.prototype.constructor = Child 以修复构造函数属性。这种组合方式实现了完整的继承机制。
构造函数窃取中 call 方法的参数传递机制是什么?
在构造函数窃取中,call 方法的第一个参数用于指定函数执行时的 this 上下文,后续参数则按顺序传递给被调用的构造函数。具体而言,Parent.call(this, name) 中的 this 是当前 Child 实例,name 是传递给 Parent 构造函数的参数。这种机制允许子类在调用父类构造函数时,灵活地传递不同的参数值,从而实现个性化的初始化逻辑。
function Parent(name, age) {
this.name = name;
this.age = age;
this.hobbies = ["reading"];
}
function Child(name, age, hobby) {
// 传递多个参数给 Parent 构造函数
Parent.call(this, name, age);
this.hobbies.push(hobby);
}
const child = new Child("Alice", 10, "swimming");
console.log(child.name); // "Alice"
console.log(child.age); // 10
console.log(child.hobbies); // ["reading", "swimming"]
上述代码展示了 call 方法在构造函数窃取中的参数传递机制。在 Child 构造函数中,通过 Parent.call(this, name, age) 将 name 和 age 传递给 Parent 构造函数。随后,Child 构造函数还可以对父类初始化的属性进行进一步操作,例如向 hobbies 数组中添加新的爱好。这种灵活的参数传递机制使得子类可以根据自身需求定制初始化逻辑。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











