Interview icon indicating copy to clipboard operation
Interview copied to clipboard

第301题(2020-09-13):ES6中的class在ES5中的实现?

Open qappleh opened this issue 5 years ago • 1 comments
trafficstars

qappleh avatar Sep 13 '20 01:09 qappleh

// es6
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    eat() {
        return  'eat'
    }
    static say() {
        return 'say'
    }
}
 
// 通过babel转换成的es5语法
"use strict";
// 判断某对象是否为某构造器的实例
function _instanceof(left, right) { 
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left); } else { return left instanceof right; }
}
 
// 检查声明的class类是否通过new的方式调用,否则会报错
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { 
    throw new TypeError("Cannot call a class as a function"); } 
}
/**
 *将方法添加到原型上,如果是静态方法添加到构造函数上,
 **/ 
 
function _defineProperties(target, props) { 
    // 遍历函数数组,分别声明其描述符 并添加到对应的对象上
    for (var i = 0; i < props.length; i++) { 
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false; // 设置该属性是否能够出现在对象的枚举属性中。默认为 false
        descriptor.configurable = true; // 设置该属性描述符能够被改变,同时该属性也能从对应的对象上被删除。
        if ("value" in descriptor) descriptor.writable = true; // 如果属性中存在value, value设置为可以改变。
        Object.defineProperty(target, descriptor.key, descriptor); // 写入对应的对象上
    }
}
 
// 收集公有函数和静态方法,将方法添加到构造函数或构造函数的原型中,并返回构造函数。
function _createClass(Constructor, protoProps, staticProps) { 
    if (protoProps) _defineProperties(Constructor.prototype, protoProps); // 共有方法写在property原型上
    if (staticProps) _defineProperties(Constructor, staticProps); // 静态方法写到构造函数上 
    return Constructor; 
}
 
var Person = function () {
    function Person(name, age) {
        _classCallCheck(this, Person);
 
        this.name = name;
        this.age = age;
    }
 
    _createClass(Person, [{
        key: "eat",
        value: function eat() {
            return 'eat';
        }
    }], [{
        key: "say",
        value: function say() {
            return 'say';
        }
    }]);
 
    return Person;
}();

qappleh avatar Oct 14 '20 07:10 qappleh