美文网首页
JavaScript ES6中 class的本质

JavaScript ES6中 class的本质

作者: 邢走在云端 | 来源:发表于2019-10-27 21:34 被阅读0次

    es6 - 代码一

    class Math {
        // 构造函数
        constructor(x,y) {
            this.x = x;
            this.y = y;
        }
    
        add() {
            return this.x + this.y;
        }
    }
    
    
    let math = new Math(1,2);
    console.log(math.add());
    

    上面的代码和java C#等如此相似

    es5 - 代码二

    
    // 一个数学计算的方法
    function Math(x, y) {
        this.x = x;
        this.y = y;
    }
    
    // 在原型中添加 add方法, 其作用是返回两个数的和
    Math.prototype.add = function() {
        return this.x + this.y;
    }
    
    var math = new Math(1,2);
    console.log(math.add())
    

    上述代码一代码二其实是一样的,es6的写法明显更为清晰和简单。

    其实,es6中的class真正的本质是一个语法糖!

    不信看下面的:大家猜猜这个Math是什么类型的

    class Math {
        // ...
    }
    console.log(typeof Math);
    

    答案是 function

    另外

    Math === Math.prototype.constructor; // true
    

    这个在 es5那段代码(代码二)中一样适合

    function Math(x, y) {
        this.x = x;
        this.y = y;
    }
    typeof Math; // "funtion"
    Math === Math.prototype.constructor; // true 
    

    放在一起:

    es5

    function Math(x, y) {
        this.x = x;
        this.y = y;
    }
    
    // 在原型中添加 add方法, 其作用是返回两个数的和
    Math.prototype.add = function () {
        return this.x + this.y;
    }
    
    var math = new Math(1,2);
    
    console.log(typeof Math);  // "function"
    
    console.log(Math === Math.prototype.constructor); // true
    
    // 实例的隐式原型 === 方法的显式原型
    console.log(math.__proto__ === Math.prototype); // true
    
    

    es6

    class Math {
        // 构造函数
        constructor(x,y) {
            this.x = x;
            this.y = y;
        }
    
        add() {
            return this.x + this.y;
        }
    }
    
    let math = new Math(1,2);
    
    console.log(typeof Math);  // "function" 
    
    console.log(Math === Math.prototype.constructor); // true
    
    // 实例的隐式原型 === 方法的显式原型
    console.log(math.__proto__ === Math.prototype); // true
    

    相关文章

      网友评论

          本文标题:JavaScript ES6中 class的本质

          本文链接:https://www.haomeiwen.com/subject/onvmvctx.html