ES6---通过class构造函数extends、public在其中的作用

来源:互联网 发布:淘宝网怎么加好友呢 编辑:程序博客网 时间:2024/06/05 18:53

在es5中,构造函数生成的对象实例一般包括私有属性和共用方法,其中共用方法一般是通过构造函数的原型进行定义。而es6中,通过class类进行定义构造函数则不用借助于原型….


class定义类:

/////////class people{    constructor(name){this.name=name}    sayName(){return 'I am '+this.name}}//constructor:构造方法,this指向对象实例,class类构造方法必须要有constctor方法;sayName:people类的方法,不需要加function,class类中的方法是不可枚举的,存在于原型中let per1=new people();//空let per2=new people('Ming');//people {name: "Ming"}per2.sayName()//"I am Ming"per2.__proto__.hasOwnProperty('sayName');//trueper2.__proto__.ccc=function(){return 'ccc'};per1.ccc();//ccc,per1和per2的__proto__指针指向相同的原型,故为per2原型增加ccc方法时,per1也同样可以调用

class中的继承:
es5中可以通过原型、call等实现继承,es6中class类可以使用extends实现继承

class people1{};class people2 extends people1{    constructor(name){        this.name=name;    }}let per=new people2('M');//报错,没有super关键字class people1{constructor(x){this.x=x}};class people2 extends people1{    constructor(x,name){        super(x);        this.name=name;    }}let per=new people2('a','M');//people2 {x: "a", name: "M"},super()方法必须使用,其用来调用父类的constructor方法,其必须放于首位。

getter和setter:

class people{    constructor(){}    get prop(){return 'i am getter'}    set prop(v){return 'i am '+v}}let per=new people();per.prop='abc';//i am abc  设置属性per.prop;//i am getter  读取属性
1 0