es5和es6继承研究

前端这点事 294 0

直接上代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
    // es5&&es6 diff
    // es5
    function Basic (name, age){
        this.name = name;
        this.age = age;
    }
    Basic.prototype.say = function (){
        console.log(this.name);
    }
    function Child (){
        var obj = Object.create(Basic.prototype);
        obj.constructor.call(obj, 'xin', 20)
        console.log(obj, obj.__proto__ === Basic.prototype)
    }
    Child()
    // es6
    // super 在静态 *** 之中指向父类,在普通 *** 之中指向父类的原型对象
    class Parent {
        constructor (name, age){
            this.name = name;
            this.age = age;
        }
        static say (){
            console.log("i 'm static say fun")
        }
        say (){
            console.log(`${this.name} is ${this.age} old`)
        }
    }
    class Child1 extends Parent {
        constructor (name, age, sex){
            super(name, age)
            this.sex = sex;
        }
        static callStaticSay (){
            super.say()
        }
        callNormalSay (){
            super.say()
        }
    }
    console.log('normal call====^', new Child1('xinxin', 29, 'man').callNormalSay());
    console.log('static call====^', Child1.callStaticSay());
    </script>
</body>
</html>


标签: JavaScript