class 理解意思

    class point{
        constructor(x,y){
            this.x = x;
            this.y = y;
        }
        toString(){
            return '[' + this.x + ',' + this.y + "]" ;
        }
    }
    var instance = new point(1,2);
    console.log('1----',instance)
//    在class中constructor方法就是构造方法,this关键字代表实例对象,toString方法实际上是protoType上的方法,方法的定义不需要加关键字,并且方法之间不能用逗号分隔。
//    注意:ES6的class中不存在变量提升,这与继承有关,必须保证子类在父类定以后使用。class内部默认就是严格模式。
    class child extends point{
        constructor(x,y,z){
         //   console.log('2----',this,x,y)//Uncaught ReferenceError: this is not defined
            super(x,y);
            console.log('3----',this,x,y)
            this.color = z;
        }
        childMethod(){
            console.log(this.z);
            return  4;

        }
    }
    var Child =new child(2,3,4);
    console.log('4----',Child,instance)
//    通过extends关键字实现继承,在子类的constructor构造函数中调用super方法,继承父类的this。同时可以添加自己的实例属性z和原型函数childMethod。

//    与ES5区别:
//    (1)在ES5中是先创建子类的this对对象,然后将父类的方法添加到this上,即Parent.apply(this)。
    // 而ES6中是用super方法创建父类的实例对象this,再用子类的构造函数修改this。因此在子类中必须调用super方法后才可以使用this。
//    (2)ES5中,每个对象都有_proto_属性,指向对应构造函数的原型对象;而prototype指向其方法的原型对象。

//    ES6中
//      子类的_proto_属性表示构造函数的继承,总是指向父类。
//      子类的prototype属性的_proto_属性表示方法的继承,总是指向父类的prototype属性。
//      子类的_proto_属性的_proto_属性,指向父类实例的_proto_属性。
//    在ES6中,使用class类实现继承,与ES5原型链继承相同的是,而子类prototype(原型对象)的__proto__属性总是指向父类的prototype(原型对象)属性,
    // 即child.prototype.__protot__ = parent.prototype。与ES5原型链继承不同的是,子类的__proto__总是指向父类,即child.__proto__ = parent
    // (注意:ES5中,child.__proto__ = Function.prototype),
//    表示构造函数的继承。而且子类__proto__的__proto__是父类的__proto__,也就是说,子类原型的原型是父类的原型。
//    class parent{
//        constructor(x,y){
//            this.x = x;
//            this.y = y;
//        }
//        toString(){
//            return '[' + this.x + ',' + this.y + "]" ;
//        }
//    }

//    //class 继承
//    class child extends parent{
//        constructor(x,y,z){
//            super(x,y); //super()创建父类的实例
//        }
//        childMethod(){
//            console.log(this.z);
//        }
//    }

//    console.log(child.__proto__ == parent); //true
//    console.log(child.prototype.__proto__ == parent.prototype); //false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值