JavaScript中子对象访问父对象的方式详解

在传统面向对象的编程语言里,都会提供一种子类访问父类特殊语法,引文我们在实现子类方法往往需要父类方法的额外辅助。在这种情况下,子类通常会调用父类中的同名方法,最终以便完成工作。

javascript虽然没有类似上述的特殊语法,但我们可以造一个啊!

rush:js;"> 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. 将usber属性设置成指向父对象的引用;

  2. 对toString()方法进行了更新;

之前的toString()方法只是简单的返回this.name,现在我们给他添加了额外的任务,就是检查this.constructor.usber属性,如果存在就调用属性的toString()方法

由于this.constructor本身是一个函数,而this.constructo.usber是指向当前对象父级原型的引用,所以我们调用child实体的toString()方法时,其原型链上的toString()方法都会被调用

rush:js;"> var my = child(1,2); my.toString() // Anna,Jock,Los

以上所述是小编给大家介绍的JavaScript中子对象访问父对象的方式详解。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...