这篇文章将为大家详细讲解有关jses6中新的类语法选项卡是怎样的,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

其实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代码:
1234
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();
}关于jses6中新的类语法选项卡是怎样的就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章名称:jses6中新的类语法选项卡是怎样的-创新互联
当前URL:http://www.scyingshan.cn/article/dcehgg.html


咨询
建站咨询
