es6 class 和 extends 的本质

2020-08-13  本文已影响0人  练习时长2年半的个人练习生

class声明的类 具有几个特点:

class 只是function 声明构造函数的语法糖。
开始手写class


     class Person{
        constructor(name){
            this.name
        }
        say(){
            console.log(this.name + '说话')
        }
     }

     var Person = function(name){      
          if(new.target === undefined){
              throw('必须使用new调用class')
          }
          this.name = name
     }
     Object.defineProperty(Person.prototype,'say',{
         value:function(){
             console.log(this.name)
         },
         enumerable:false
     })

     let p = new Person('实例')
     p.say()

class 声明类的本质就是下面 手写这个function

extends 的本质

 class Animal {
        constructor(){

        }
        eat(){
            console.log('吃东西')
        }
    }
    class Person extends Animal {
        constructor(name) {
            super()
            this.name = name
        }
        say() {
            console.log(this.name + '说话')
        }
    }

    const p = new Person('张三')

    p.eat() //吃饭
    p.say()//张三说话

他的本质

    function Animal(type){
        this.type = type
    }
    Animal.prototype.eat = function(){
        console.log('吃饭')
    }
 
    function Person(name){
        Animal.call(this,'动物') //super的本质
        this.name = name 
    }
    Person.prototype = Object.create(Animal.prototype)
    Person.prototype.constructor = Person
    Person.prototype.say=function(){
        console.log('我叫'+this.name)
    }
    var p = new Person('张三');
    p.eat()//吃饭
    p.say()//我叫张三

super的本质,是在子类执行父类的方法,然后把this绑定执行一遍

上一篇 下一篇

猜你喜欢

热点阅读