JavaScript子对象访问父对象:通过uber属性实现原型链调用

作者:异步漫步时间:2026-10-31 02:25:25浏览:321

本文详解在JavaScript中子对象访问父对象的方法。通过引入uber属性指向父级原型,重写toString等方法,实现子类调用父类同名方法。结合示例代码,解析原型链上的方法查找与执行机制,帮助理解JS继承与多态实现。

传统面向对象与JavaScript的差异

在传统面向对象编程语言中,通常提供子类访问父类的特殊语法,因为实现子类方法时往往需要父类方法的辅助。此时,子类通常会调用父类中的同名方法以完成工作。

JavaScript虽无此类特殊语法,但我们可以手动实现类似机制。

通过uber属性实现父对象访问


function her(){};
her.prototype.name = 'Anna';
her.prototype.toString = function(){
var const = this.constructor;
return const.uber ? this.const.uber.toString() + ',' + this.name : this.name;
}
function his(){};
var F = function(){};
F.prototype = her.prototype;
his.prototype = new F();
his.prototype.constructor = her;
his.uber = her.prototype;
his.prototype.name ='Jock';
function child(width, height){
this.width = width;
this.height = height;
}
var F = function(){};
F.prototype = his.prototype;
child.prototype = new F();
child.prototype.constructor = child;
child.uber = his.prototype;
child.prototype.name = 'Los';
child.prototype.getArea = function(){
return this.width * this.height;
}

在构建对象关系时,引入一个uber属性,使其指向父级对象。

具体更新内容如下:

1. 将uber属性设置为指向父对象的引用;

2. 更新toString()方法;

原toString()仅返回this.name,现增加逻辑:检查this.constructor.uber属性,若存在则调用该属性的toString()方法。

由于this.constructor是函数,而this.constructor.uber指向当前对象父级原型,调用child实体的toString()时,其原型链上的toString()方法会被依次调用。


var my = child(1,2);
my.toString() // Anna, Jock, Los

以上介绍了JavaScript中子对象访问父对象的方式,希望对大家有所帮助。如有疑问请留言,小编会及时回复。感谢支持!

作者最新文章