简体   繁体   English

严格模式下对象的类型是否可变?

[英]Variable typeof object in strict mode?

This piece of JavaScript ran fine without "use strict"; 这段JavaScript在没有"use strict";情况下运行良好"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? 但是,如何在严格模式下检查全局变量是否存在以及它具有什么类型,而不会遇到undeclared variable错误?

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. typeof a应该仍然可以像以前一样工作。

I found a valid way to check if a global variable a exists without triggering a warning in JavaScript. 我找到了一种有效的方法来检查全局变量a存在而无需在JavaScript中触发警告。

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property. hasOwnProperty()方法返回一个布尔值,指示对象是否具有指定的属性。

hasOwnProperty() does not trigger a warning when the requested variable name does not exist in the global space! 当所请求的变量名在全局空间中不存在时, hasOwnProperty()不会触发警告!

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

To make sure a is an object use 确保a是对象使用

'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 = {}; 问题是您有一个未声明的变量...您必须首先输入: 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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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