博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
es6中class类的全方面理解(二)------继承
阅读量:6975 次
发布时间:2019-06-27

本文共 2662 字,大约阅读时间需要 8 分钟。

继承是面向对象中一个比较核心的概念。ES6 class的继承与java的继承大同小异,如果学过java的小伙伴应该很容易理解,都是通过extends关键字继承。相较于ES5当中通过原型链继承要清晰和方便许多。先上代码:

class Cucurbit{    constructor(name,color){        console.log("farther")        this.name=name;        this.color=color;    }    say(){        console.log("我的名字叫"+this.name+"我是"+this.color+"颜色的");    }}class First extends Cucurbit{    constructor(name,color){        super(name,color);// 调用父类的constructor(name,color)    }    say(){        console.log("我是child");        super.say();    }}var wa=new First("大娃","红色");wa.say();

输出:

farther我是child我的名字叫大娃我是红色颜色的

上面代码中,子类的constructor方法和say方法中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。 

子类必须在constructor方法中调用super方法,之后才能使用this关键字,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象。如果不调用super方法,子类就得不到this对象。在这一点上ES5的继承与ES6正好相反,ES5先创建自己的this对象然后再将父类的属性方法添加到自己的this当中。 
如果子类First没有显式的定义constructor,那么下面的代码将被默认添加(不信可以尝试下,哈)。换言之,如果constructor函数中只有super的话,该constructor函数可以省略。

constructor(name,color){        super(name,color);// 调用父类的constructor(name,color)}

总结super在子类中一般有三种作用

1.作为父类的构造函数调用(已说明)

2.在普通方法中,作为父类的实例调用(已说明)

3.在静态方法中,作为父类调用(下篇文章会做介绍)

实例

创建一个tab切换,页面中有三个按钮内容分别为“中”,“日”,“韩”。要求点击按钮,按钮以及切换的内容的背景颜色分别会变为红,黄,绿。

首先创建一个tab.html页面,内容为:

    
切换
中国
日本
韩国

然后创建一个tag.js,内容为:

class Tag{    constructor(id){        this.id=document.querySelector(id);        this.btn=this.id.querySelectorAll("input");        this.div=this.id.querySelectorAll("div");        this.colorArr=["red","yellow","green"];        this.index=0;//显示元素的下标。        this.init();    }    init(){
//初始化 this.hide(); this.show(); //给按钮增加事件 for(let i=0;i

示例到现在还没有用到ES6的继承啊,别急!咱们再加个需求,在上面的切换示例基础上,再加一个内容为“娱乐”,“体育”,”财经”的切换。该切换需要在原来可点击的基础上实现自动切换功能,以及点击页面空白区域也可实现切换。

将tag.html页面修改为:

    
切换
中国
日本
韩国
娱乐
财经
体育

将tag.js修改为:

class Tag{    constructor(obj){        this.id=document.querySelector(obj.id);        this.btn=this.id.querySelectorAll("input");        this.div=this.id.querySelectorAll("div");        this.colorArr=obj.colorArr;        this.index=obj.index;//显示元素的下标。        this.init();    }    init(){
//初始化 this.hide(); this.show(); var that=this; //给按钮增加事件 for(let i=0;i
=this.btn.length) this.index=0; this.hide(); this.show(); }}

 

转载于:https://www.cnblogs.com/catbrother/p/9397175.html

你可能感兴趣的文章
javascrpt 类详解 面向对象
查看>>
POJ3671 Dining Cows
查看>>
UVa10214 Trees in a Wood.
查看>>
使用WebBrowser控件播放Flash网页相关问题解决方法(转)
查看>>
UVA - 10815 - Andy's First Dictionary STL
查看>>
清除SQL server 记住的用户名和密码
查看>>
URL 字符编码
查看>>
[vijos P1023] Victoria的舞会3
查看>>
C ++模板的声明和实现为何要放在头文件中?
查看>>
keychains
查看>>
混频器
查看>>
系统利益相关者描述
查看>>
IDENTITY
查看>>
unity3d游戏开发学习分享之表面着色器讲解
查看>>
Apache的三种工作模式
查看>>
dlib编译成静态库及被其它程序调用
查看>>
UNIX网络编程之epoll的 accept , read , write
查看>>
java事务管理
查看>>
分布式MySQL 数据库
查看>>
MMX指令集系列之一----数据加载与算术运算指令
查看>>