新的类语法实战选项卡(详解)

其实es6的面向对象很多原理和机制还是ES5的,只不过把语法改成类似php和java老牌后端语言中的面向对象语法.

一、用es6封装一个基本的类

class Person{ constructor( uName ){ this.userName = uName; } sayName(){ return this.userName; } }

是不是很向php和java中的类, 其实本质还是原型链,我们往下看就知道了

首先说下语法规则:

class Person中的Person就是类名,可以自定义

constructor就是构造函数,这个是关键字,当实例化对象的时候,这个构造函数会被自动调用

let oP = new Person( 'ghostwu' ); console.log( oP.sayName() ); //ghostwu console.log( oP instanceof Person ); //true console.log( oP instanceof Object ); //true console.log( typeof Person ); //function console.log( typeof Person.prototype.sayName ); //function console.log( oP.__proto__ === Person.prototype ); //true console.log( 'sayName' in oP ); //true console.log( Person.prototype );

第1行和第2行实例化和调用方法还是跟es5一样

第4行和第5行判断对象是否是类(Person)和Object的实例, 结果跟es5一样, 这个时候,我们肯定会想到Person的本质是否就是一个函数呢

第7行完全验证了我们的想法,类Person本质就是一个函数

第8行可以看到sayName这个函数其实还是加在Person的原型对象上

第9行还是验证了es5的原型链特点:对象的隐式原型指向构造函数的原型对象

第10行验证oP对象通过原型链查找到sayName方法

这种类的语法,被叫做语法糖,本质还是原型链

二、利用基本的类用法,封装一个加法运算

class Operator{ constructor( n1 = 1, n2 = 2 ){ this.num1 = n1; this.num2 = n2; } add( n1 = 10, n2 = 20 ){ let num1 = n1 || this.num1, num2 = n2 || this.num2; return num1 + num2; } } var oper = new Operator(); console.log( oper.add( 100, 200 ) );

三、利用基本的类语法,封装经典的选项

css代码:

#tab div { width: 200px; height: 200px; border: 1px solid #000; display: none; } #tab div:nth-of-type(1) { display: block; } .active { background: yellow; }

html代码:

<div> <input type="button" value="点我1" data-target="#div1"> <input type="button" value="点我2" data-target="#div2"> <input type="button" value="点我3" data-target="#div3"> <input type="button" value="点我4" data-target="#div4"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div>

javascript代码:

window.onload = () => { class Tab { constructor( context ) { let cxt = context || document; this.aInput = cxt.querySelectorAll( "input" ); this.aDiv = cxt.querySelectorAll( "div" ); } bindEvent(){ let targetId = null; this.aInput.forEach(( ele, index )=>{ ele.addEventListener( "click", ()=>{ targetId = ele.dataset.target; this.switchTab( ele, targetId ); }); }); } switchTab( curBtn, curId ){ let oDiv = document.querySelector( curId ); this.aDiv.forEach(( ele, index )=>{ ele.style.display = 'none'; this.aInput[index].className = ''; }); curBtn.className = 'active'; oDiv.style.display = 'block'; } } new Tab( document.querySelector( "#tab" ) ).bindEvent(); }

以上这篇js es6系列教程 - 新的类语法实战选项卡(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wygjsy.html