IE8下Object.defineproperty兼容性问题解决
2017/07/14    标签: anujs    anu    IE8下Object.defineproperty   

这两天捣鼓anu的例子

anu是什么?

anu是司徒正美大神17年左右刚出的新框架。可以无痛替换掉react。

关于anu的介绍,请看官网https://rubylouvre.github.io/anu/

会react的anujs是拿来就可以用的。


react的学习请移步阮一峰大神的13个demo(13这个数字不错)

http://www.ruanyifeng.com/blog/2015/03/react



学习这些的我们也经常会用到class构造函数。

例如:

class Point {    
    constructor(x, y) {        
        this.x = x;        
        this.y = y;
    }
    toString() {        
        return `(${this.x}, ${this.y})`;
    }
}

为了使class构造兼容到低版本IE。

用babel的es2015插件打包。默认打包结果如下:

"use strict";

var _createClass = (function () {
    function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value" in descriptor) descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor); // (A)
        }
    }
    return function (Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
    };
})();

function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}

var Point = (function () {
    function Point(x, y) {
        _classCallCheck(this, Point);

        this.x = x;
        this.y = y;
    }

    _createClass(Point, [{
        key: "toString",
        value: function toString() {
            return "(" + this.x + ", " + this.y + ")";
        }
    }]);

    return Point;
})();

生成的代码里有Object.defineProperty,这个在ie8下不兼容(ie8下Object有这个方法,只是用法不一样)。

我们需要在使用插件的时候这么配置:

presets:[["es2015",{
            "loose" : true,//解决Object.defineProperty
            "modules" : false
          }]

修改配置后的打包代码:

"use strict";

function _classCallCheck(instance, Constructor) { ··· }

var Point = (function () {
    function Point(x, y) {
        _classCallCheck(this, Point);

        this.x = x;
        this.y = y;
    }

    Point.prototype.toString = function toString() { // (A)
        return "(" + this.x + ", " + this.y + ")";
    };

    return Point;
})();

参考:

http://2ality.com/2015/12/babel6-loose-mode.html

https://github.com/bkonkle/babel-preset-es2015-loose

http://www.aliued.com/?p=3240&utm_source=tuicool&utm_medium=referral

http://babeljs.cn/docs/usage/options/