ES6 class的应用实例分析
本文实例讲述了ES6class的应用。分享给大家供大家参考,具体如下:
class
- class本身是个语法糖,主要为了考虑在编码上更加人性化
- 内部有super,static,get等关键词
- 使用起来非常类似于后台语言
使用class进行类的实现应用
'usestrict';
//User类
classUser{
constructor(name,age){
this.name=name;
this.age=age;
}
staticgetName(){
return'User';
}
staticgetAge(){
returnthis.age;
}
setName(name){
this.name=name;
}
setAge(age){
this.age=age;
}
getinfo(){
return'name:'+this.name+'|age:'+this.age;
}
}
//Manager类
classManagerextendsUser{
constructor(name,age,password){
super(name,age);
this.password=this.password;
}
changePwd(pwd){
returnthis.password=pwd;
}
getinfo(){
varinfo=super.info;//使用super继承父级get
returninfo+'===new';
}
}
//typeofUser:functiontypeofManager:function
console.log('typeofUser:',typeofUser,'typeofManager:',typeofManager);
letmanager=newManager('Li',22,'123456');
manager.setAge(23);
console.log(manager.info);//name:Li|age:23===new
console.log(User.prototype);
console.log(Manager.prototype);
在class之前使用原型对象定义类的应用
//构造函数
functionUser(name,age){
this.name=name;
this.age=age;
}
//原型
User.prototype={
getName:function(){
return'User';
},
setName:function(name){
this.name=name;
},
getAge:function(){
returnthis.age;
},
setAge:function(age){
this.age=age;
}
}
//取值函数和存执函数
Object.defineProperty(User.prototype,'info',{
get(){
return'name:'+this.name+'|age:'+this.age;
}
});
varuser=newUser('Joh',26);
console.log(user);//User{name:"Joh",age:26}
//子类
functionManager(name,age,password){
User.call(this,name,age);
this.password=password;
}
Manager.__proto__=User;//继承静态方法
Manager.prototype=Object.create(User.prototype);//继承prototype原型方法
Manager.prototype.changePwd=function(pwd){
this.password=pwd;
};
varmanager=newManager('Li',22,'123456');
manager.setAge(23);
console.log(manager.info);//name:Li|age:23
console.log(User.prototype);//不变
console.log(Manager.prototype);//{changePwd:function(){},info:"name:undefined|age:undefined",__proto__:指向Manager.prototype}
使用class定义的类不被提升,需按顺序执行
正常:
letuser=newclassUser{
constructor(name){
this.name=name;
}
}('Joh');
console.log(user);//User{name:"Joh"}
错误:
varman=newMan();//此处报错,使用class声明的类不会被提升UncaughtReferenceError:Manisnotdefined
classMan{
constructor(name){
this.name=name;
}
}
更多关于JavaScript相关内容可查看本站专题:《javascript面向对象入门教程》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。