zoukankan      html  css  js  c++  java
  • 继承之es5对比es6

    es5 写法:

    function Person(name){
        this.name = name;
    }
    
    Person.prototype.sayName = function() {
        alert(this.name);
    }  
    
    function VipPerson(name,level){
      Person.call(this,name);
      this.level = level;
    }  
    // 组合继承(缺点是prototype这一层多了一些无用的undefined属性)
    // VipPerson.prototype = new Person();
    // VipPerson.prototype.constructor = VipPerson; //重写construtor
    
    // 寄生组合继承
    VipPerson.prototype = Object.create(Person.prototype, {
        constructor: { //重写construtor
            value: VipPerson,
            enumerable: false,
            configurable: true,
            writable: true
        }
    })
    
    var vipPerson = new VipPerson('amie',3);

    es6的写法:

    相比于es5,es6的写法简化了很多,extends、super就可以完成上面寄生组合继承的效果

    super,可以看成 Person.call(this, name)

    class Person{
        constructor(name){
            this.name = name; 
        }
        sayName(){
           alert(this.name);      
        }
    }
    
    class VipPerson extends Person{
        constructor(name,level){
            super(name);
            this.level = level;
        }
    }    
    
    var person2 = new VipPerson('rick',3)
  • 相关阅读:
    电赛小结
    markdown小结
    一元运算符重载
    二维数组作为函数参数传递剖析(转载)
    C语言内存(转载)
    Effective C++ chapter1:Accustiming Yourself to C++
    C++ 模板
    const
    命令行参数
    AStar算法
  • 原文地址:https://www.cnblogs.com/amiezhang/p/6440582.html
Copyright © 2011-2022 走看看