我是HTML

es6-class

 /*类的数据类型就是函数,类本身就指向构造函数*/
    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            console.log(this);
        }

        fn() {
            return this.x + this.y
        }
    }
    let a = new Point(1, 2);
    console.log(a.fn === a.fn)
    console.log(Point.prototype)

    class Man {
        constructor(name, age) {
            console.log(`Man类的this指向+${this}`, this);
            this.name = name;
            this.age = age;
        }

        say() {
            return this.name+this.age;

        }
    }
    let hxq = new Man('hxq', 18);
    console.log('hxq实例', hxq);
    console.log(hxq.__proto__);
    console.log(Man.prototype);
    console.log(Man.prototype===hxq.__proto__)  //true
    console.log(hxq.say===Man.prototype.say) //true  类的实例上调用方法其实就是调用原型上的方法
    console.log(Man.prototype);

//    Object.assign(Man.prototype,{}) 用来一次性给原型添加多种方法
    Object.assign(Man.prototype,{
        eat(){},
        drink(){}
    })
    console.log(Man);
    console.log(Object.getOwnPropertyNames(hxq.__proto__))//["constructor", "say", "eat", "drink"]


 

 /*
    * 所有类的实例共享一个原型对象
    * class的类不存在变量提升与es5异 在类上方实例化一个对象会报错(let也不存在变量提升)*/
    class Man{
        constructor(name,age){
            /*写在这里面的是自身的属性可用hasOwnProperty()检测*/
            this.name=name;
            this.age=age;
            console.log('constructor里的函数自动执行')
//            return Object.create(null);//改变Man里this的指向 constructor返回一个全新的对象导致hxq不是man的实例
        }
        say(){
            return this.name+this.age
        }

    }
    let hxq=new Man('hxq',28);
    console.log(hxq instanceof Man);//hxq是来自Man的实例
    console.log(hxq.say())

 __proto__ and prototype 绕来绕去


class People { constructor(name, age) {
this.name = name; this.age = age; } say() { return this.name + this.age; } } class Man extends People { constructor(name, age,drink) { super(name, age);//如果没有super(),在实例化对象的时候会报错;其中的this就继承自父级;如在super()上方使用this则会报错 this.drink=drink; } } var hxq = new Man('xhq', 18); console.log(hxq);//Man {name: "xhq", age: 18} console.log(Man.prototype.constructor===Man); console.log(hxq.__proto__);//实例的对象的__proto__===其构造函数的prototype console.log(Man.prototype.constructor.__proto__);//与下相等 console.log(Man.__proto__);//子级原型上的构造函数的__proto__指向父级的构造函数 (是一个函数) console.log(hxq instanceof People);//true; console.log(hxq instanceof Man);//true;

 

posted @ 2017-09-22 10:56  你值得拥有xxx  阅读(230)  评论(0编辑  收藏  举报