获取 ES6 中值的类型

5 javascript ecmascript-6 babeljs

我正在使用带有 ["iife-wrap"] 插件的 ES6 + babel。

我正在尝试重新制作我之前创建的插件(表单验证)。我正在尝试检查数据是否为对象。

对于 es5,这只是:typeof blah === 'object'string, function, and etc.

但是如果我把它放在 es6. 它会产生Uncaught TypeError: _typeof is not a function 的错误

这是我的代码示例。

let es6function = () => {
    return 'asd';
}

console.log(typeof es6function)

class Person {

}

let tryThis = new Person()
console.log(tryThis instanceof Person)
Run Code Online (Sandbox Code Playgroud)

ES5:后编译

;

(function () {
    'use strict';

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

    var _typeof = typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol" ? function (obj) {
        return typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
    } : function (obj) {
        return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
    };

    var es6function = function es6function() {
        return 'asd';
    };

    console.log(typeof es6function === 'undefined' ? 'undefined' : _typeof(es6function));

    var Person = function Person() {
        _classCallCheck(this, Person);
    };

    var tryThis = new Person();
    console.log(tryThis instanceof Person);
})();
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。谢谢。

Ber*_*rgi 3

看起来您不小心在代码上两次运行了 Babel。

ES6 代码

console.log(typeof es6function)
Run Code Online (Sandbox Code Playgroud)

会被转译为

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

console.log(typeof es6function === 'undefined' ? 'undefined' : _typeof(es6function));
Run Code Online (Sandbox Code Playgroud)

这确实成为

var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
    return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};

console.log(typeof es6function === 'undefined' ? 'undefined' : _typeof(es6function));
Run Code Online (Sandbox Code Playgroud)

当你再次转译它时。除了_typeof/_typeof2重复之外,这看起来确实很像您的转译结果。检查你的构建配置和 babel 插件。尝试依次禁用一个,看看问题何时会消失,并向负责的组件报告错误。