简体   繁体   中英

Variable typeof object in strict mode?

This piece of JavaScript ran fine without "use strict"; . But how can I check if a global variable exists with strict mode and what type it has without running into a undeclared variable error?

if (!(typeof a === 'object')) {
    a = ... /* complex operation */
}

Creating implicit globals is an error in strict mode. You have to create the global explicitly:

window.a = ... /* complex operation */

typeof a should still work as before.

I found a valid way to check if a global variable a exists without triggering a warning in JavaScript.

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property.

hasOwnProperty() does not trigger a warning when the requested variable name does not exist in the global space!

'use strict';
if (!window.hasOwnProperty('a')) {
    window.a = ... 
    // Or
    a = ...
}

To make sure a is an object use

'use strict';
if (!(window.hasOwnProperty('a') && typeof a === 'object')) {
    window.a = ... 
    // Or
    a = ...
}

The problem is you have a non declared variable... you must put this first: var a = {}; . But, here is how I check those kind of things.

var utils = {
  //Check types
  isArray: function(x) {
    return Object.prototype.toString.call(x) == "[object Array]";
  },
  isObject: function(x) {
    return Object.prototype.toString.call(x) == "[object Object]";
  },
  isString: function(x) {
    return Object.prototype.toString.call(x) == "[object String]";
  },
  isNumber: function(x) {
    return Object.prototype.toString.call(x) == "[object Number]";
  },
  isFunction: function(x) {
    return Object.prototype.toString.call(x) == "[object Function]";
  }
}

var a = ""; // Define first, this is your real problem.
if(!utils.isObject(a)) {
  // something here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM