多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
~~~ // Es6类 class Persion2{ //构造函数 必须constructor constructor(name,age){ this.name=name; this.age=age; } //方法:必须方法名+()+{} say4(){ console.log(this.name+this.age) } } var Persion4=new Persion2("dash4",21); console.log(Persion4); Persion4.say4(); ~~~ ``` function person(){ } //向函数对象追加属性,即向Function追加属性 person.name="tom"; person.say=function(){console.log("hello world!")} //向原型对象追加属性(实例对象可访问)相当于向父类追加属性 person.prototype.sex="男"; var p=new person(); console.log(person.name);//tom console.log(p.name);//undefined console.log(p.sex);//男 //函数对象的属性属于类,不属于实例对象 //在Es6中 函数对象用static声明 class person{ constructor(sex) { this.sex="男"; } static name= "tom"; static say(){ console.log("hello world!"); } } let p=new person(); console.log(person.name)//tom console.log(p.name);//undefined console.log(p.sex);//男 ``` ## **继承与方法重写** ``` // 老版本 function User(name, pass) { this.name = name this.pass = pass } User.prototype.showName = function () { console.log(this.name) } User.prototype.showPass = function () { console.log(this.pass) } var u1 = new User('able', '1233') u1.showName() u1.showPass() // 老版本继承 function VipUser(name, pass, level) { //call()它可以用来调用所有者对象作为参数的方法 //通过call(),您能够使用属于另一个对象的方法 User.call(this, name, pass) this.level = level } VipUser.prototype = new User() VipUser.prototype.constructor = VipUser VipUser.prototype.showLevel = function () { console.log(this.level) } var v1 = new VipUser('blue', '1234', 3) v1.showName() v1.showLevel() ``` ES6 ``` class User { constructor(name, pass) { this.name = name this.pass = pass } showName() { console.log(this.name) } showPass() { console.log(this.pass) } } var u1 = new User('able2', '111') u1.showName() u1.showPass() // 新版本继承 class VipUser extends User { constructor(name, pass, level) { super(name, pass) this.level = level } showLevel(){ console.log(this.level) } //重写父类方法 showName() { console.log("重写啦!") } } v1 = new VipUser('blue', '123', 3) v1.showLevel() v1.showName() ``` ## **getter与setter** get:当获取属性是触发 set当设置属性树触发 ``` class person{ get age(){ console.log("获取年龄"); } set age(age){ console.log("设置年龄"); } } let p=new person(20); p.age=20 p.age ```