1.定义
// es5封装一个对象 function Person(name,age){ this.name = name; this.age = age; } Person.prototype.run = function(){ console.log(this.name+" is running"); } let p = new Person('lily'); p.run(); // ES6类的定义 calss Person{ //构造方法 constructor(name,age){ this.name = name; this.age = age; } //方法 /* 函数的定义一定要用简写的方式,必须省略function 写在class中的方法,是定义在类的原型上的 */ run(){ console.log(this.name+" is running"); } } //实例化 let p = new Person('lily',300); p.run(); console.log(p);
总结:
1.class中的方法都是定义在prototype上
2.class中的方法都必须是简写,不带function
3.calss中的构造函数用counstructor来定义
4.class类方法,不能直接调用,必须实例化
2.class中的getter和setter
class Animal{ set prop(name){ this.name = name; } get prop(){ return this.name; } set age(value){ if(value<13){ this.ages = value; }else{ this.ages = 0 } } get age(){ return this.age } } /* 当没有constructor,系统会默认一个空参 */ let ani = new Animal(); ani.prop = "tiger"; console.log(ani.pro); ani.age = 13; console.log(ani.age);
// 传统的方法定义 function Person(){} Person.eat = function(){ console.log('eating'); } person.eat(); // es6 class Animal(){ constructor(color){ this.color = color; } static run(){ //静态方法中的this是指向类本身就是Animal本身,不是指向new实例化的 console.log(this); } } let rabbit = new Animal('white'); Animal.run();//'undefined' let rabbit = new Animal('white');//black //给class添加静态属性 Animal.color = 'black'; Animal.run();//black
4.new target
构造函数被调用的时候,this指向谁
只有通过new调用构造函数里,new.target才指向构造函数
其它情况都返回undefined
function Person(){ console.log(new.target); } new Person();//指向Person Person.call(); Person.apply(); Person(); ==== function Person(){ console.log(new.target); if(new.target === Person){ this.name = name; }else{ thorw new Error('只能通过new来调用'); } } new Person();//指向Person,所有不报错 Person.call();//报错 Person.apply();//报错 Person();//报错
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。