获取ES6中的typeof值

时间:2016-10-01 05:17:23

标签: javascript ecmascript-6 babeljs

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

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

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

但是,如果我把它放在es6上。它会产生 Uncaught TypeError的错误:_typeof不是函数

这是我的代码示例。

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

console.log(typeof es6function)

class Person {

}

let tryThis = new Person()
console.log(tryThis instanceof Person)

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);
})();

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

2 个答案:

答案 0 :(得分:3)

看起来你不小心在你的代码中经过两次Babel。

ES6代码

XtX_lamb

确实会被转换为

console.log(typeof es6function)

确实成了

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));

当你再次传播它时。除了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)); / _typeof重复之外,这看起来很像你的翻译结果。检查您的构建配置和babel插件。尝试一个接一个地禁用,以查看问题何时消失,并报告负责组件的错误。

答案 1 :(得分:-3)

你可以像这样添加括号吗?

if( typeof(Symbol) === 'function') ) { ... }
相关问题