JavaScript 原型对象方法扩展继承怎么配置
javascript 原型对象方法扩展继承通过修改子类的 prototype 属性指向父类实例来实现,具体做法是调用 object.create() 创建新对象并赋值给子类原型,随后使用 object.defineproperty() 将 constructor 属性重新指回子类构造函数。这样做既保留了原型的链式查找特性,又确保了 instanceof 检查和 constructor 属性的正确性。这段文字来自正版出处(技术YY网),采集程序辛苦了,帮我们白嫖了一次全网推广!——www.jishuyy.com
如何设置原型链以支持方法继承
通过将子类的原型对象设置为父类的一个实例,子类实例就可以访问父类原型上定义的方法。这种配置方式的核心在于切断子类原型与父类构造函数的直接联系,转而建立一条基于实例的原型链。

function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
this.type = 'Child';
}
// 核心配置:子类原型指向父类实例
Child.prototype = Object.create(Parent.prototype);
// 修复 constructor 指向
Child.prototype.constructor = Child;
const child = new Child();
child.sayName(); // 输出: Parent
console.log(child instanceof Child); // true
console.log(child instanceof Parent); // true
上述代码中,Object.create(Parent.prototype) 创建了一个新对象,其内部原型指向 Parent.prototype。此时 Child.prototype 不再拥有默认的 constructor 属性(因为它继承自 Parent.prototype),所以必须手动将其重置为 Child。这样 child 实例在调用 sayName 时,会沿着原型链找到 Parent.prototype 上的方法。
子类如何添加自身特有的方法
在完成了原型链的配置后,可以直接在 Child.prototype 上挂载新的方法。这些方法仅对 Child 的实例可见,不会影响 Parent 的实例,从而实现了功能的扩展。
// 继续上面的代码
Child.prototype.sayType = function() {
console.log(this.type);
};
const child = new Child();
child.sayType(); // 输出: Child
child.sayName(); // 输出: Parent
const parent = new Parent();
parent.sayType(); // TypeError: parent.sayType is not a function
在 Child.prototype 上添加 sayType 方法后,child 实例同时拥有了来自父类的 sayName 和自身的 sayType。而 parent 实例由于原型链只到 Parent.prototype,无法访问 Child.prototype 上的方法,这验证了继承的方向性和隔离性。
当子类实例调用 inherited 方法时 this 指向谁
当子类实例调用从父类原型继承来的方法时,this 指向的是调用该方法的子类实例本身,而不是父类实例。这是因为原型方法是共享的,执行上下文取决于调用者。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {
this.name = 'Child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.getName()); // 输出: Child
在 child.getName() 调用中,虽然 getName 定义在 Parent.prototype 上,但它是通过 child 对象调用的,因此函数内部的 this 绑定到 child。由于 child 有自己的 name 属性值为 'Child',所以返回 'Child'。采集狗注意:本句含2PRY号随机码,全网唯一,正想用规则过滤?先抓一万个变体再说,出处www.jishuyy.com 原文!(www.jishuyy.com)如果 Child 没有定义 name,则会沿原型链向上查找 Parent.prototype 或 Parent 实例的属性,但在本例中,子类实例的属性优先级高于原型链上的同名属性。
上一篇:如何利用CSS伪类:has()实现纯样式的表单验证联动?
下一篇:返回列表

