A summary of the usage of typeof in js

  • 2020-03-30 00:53:54
  • OfStack

Typeof in JavaScript is actually quite complex and can do a lot of things, but it also has a lot of weird behavior.

(link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof? Redirectlocale = en - US&redirectslug = JavaScript % 2 freference % 2 foperators % 2 ftypeof)

      > Typeof undefined
      "Undefined"
      > Typeof null // well-known bug
      'object'
      > Typeof true
      'Boolean'
      > Typeof 123
      'number'
      > Typeof "ABC"
      'string'
      > Typeof function () {}
      'function'
      > Typeof {}
      'object'
      > Typeof []
      'object'
      > Typeof unknownVariable
      "Undefined"

1. Check if a variable exists and has a value.
Typeof returns "undefined" in two cases: when a variable is not declared, and when the value of a variable is undefined. For example:

> Typeof undeclaredVariable === "undefined" true > Var declaredVariable; > Typeof declaredVariable 'undefined > Typeof undefined "undefined"
There are other ways to check if a value is undefined:

> Var value = undefined; > Value = = = undefined true
However, this method will throw an exception if used on an undeclared variable, because only typeof can normally detect an undeclared variable without reporting an error:

> UndeclaredVariable === undefined ReferenceError: undeclaredVariable is not defined
Note: variables that are not initialized, parameters that are not passed in, and attributes that do not exist do not have the same problem as above, because they are always accessible and the value is always undefined:

> Var declaredVariable; > DeclaredVariable === undefined true > Function (x) {return x === undefined}()) ({}). Foo = = = undefined true
Translator's note: so, if you want to test a may not have been declared a global variable exists, can also be used if (window. MaybeUndeclaredVariable) {}


Problem: typeof is cumbersome for such tasks.

Solution: this is not very common, so some people don't feel the need to find a better solution.

> Defined undeclaredVariable false > Var declaredVariable; > Defined declaredVariable false
Or, perhaps one needs an operator that checks whether a variable is declared:

> Declared undeclaredVariable false > Var declaredVariable; > Declared declaredVariable true
In perl, the defined operator above corresponds to defined(), and the declared operator above corresponds to exists(),

2. Determine that a value is not undefined or null
Problem: if you want to check if a value has been defined (not undefined or null), then you encounter one of the most famous quirks of typeof (thought to be a bug):typeof null returns "object":

> Typeof null 'object'
Translator's note: this is only the initial JavaScript implementation bugs, and now this is standard specification. V8 was revised and implement a typeof null = = = "null", but in the end prove unworkable. http://wiki.ecmascript.org/doku.php? Id = harmony: typeof_null


Solution: instead of using typeof for this task, use the following function instead:

Function isDefined(x) {return x! == null && x! = = is undefined. }
Another possibility is to introduce a "defaultValue operator", where the following expression returns defaultValue if myValue is not defined:

MyValue?? defaultValue
The above expression is equivalent to:

(myValue! == undefined && myValue! = = null)? MyValue: defaultValue
Or:

MyValue?? = defaultValue
It's a simplification of the following statement:

MyValue = myValue?? defaultValue
When accessing a nested property, such as bar, you may need the help of this operator:

Obj. Foo. Bar
If obj or obj.foo is undefined, the above expression throws an exception. You can have the above expression return the first undefined or null property encountered as it traverses the properties of the layer after layer:

Obj.?? Foo.?? The bar
The above expression is equivalent to:

(obj === undefined || obj === null)? Obj: (obj.foo === undefined || obj.foo === null)? Obj. Foo: obj. Foo. Bar

3. Distinguish between object values and primitive values
The following function checks whether x is an object value:

Function isObject(x) {return (typeof x === "function" || (typeof x === "object" &&x! = = null)); }
Problem: the above detection is more complicated because typeof treats functions and objects as different types, and typeof null returns "object".

Solution: the following methods are also often used to detect object values:

Function isObject2(x) {return x === Object(x); }
Warning: you might think that instanceof Object could be used here, but instanceof is used to determine instance relationships by using a prototype that USES an Object, so what about objects that don't have a prototype:

> Var obj = Object. The create (null); > A null Object. GetPrototypeOf (obj)
Obj is indeed an object, but it is not an instance of any value:

> Typeof obj 'object' > Obj instanceof Object false
In practice, you may not come across such an object very often, but it does exist and has a purpose.

Prototype is a default Object with no prototype

> Object. GetPrototypeOf (Object. The prototype) null> Typeof Object. The prototype 'Object' > Object. The prototype instanceof Object false

4. What is the type of the original value?
Typeof is the best way to view the typeof a primitive value.

> "ABC" typeof 'string' > Typeof undefined "undefined"
Problem: you must be aware of the weird behavior of typeof null.

> Typeof null // be careful! 'object'
Solution: the following function fixes the problem (for this use case only).

Function getPrimitiveTypeName(x) {var typeName = typeof x; Switch (typeName) {case "undefined": case "Boolean ": case "number": case "string": return typeName; Case "object": if (x === null) {return "null"; } default: // the previous judgment fails to pass throw new TypeError(" parameter is not a original value: "+x "); }}

A better solution: implement a function getTypeName() that returns both the type of the original value and the internal [[Class]] property of the object's value.

5. Is a value a function
Typeof can be used to detect whether a value is a function. Typeof function () {} 'function' >   Typeof Object. The prototype. ToString 'function'

In principle,instanceof Function can also test the demand. At first glance, looks like the writing is more elegant. However, the browser has a quirk: each frame and window has its own global variables. Therefore, if you will be a framework in the frame of the object to another, instanceof can't work normally, because the two frameworks have different constructor. This is why there will be an Array. In ECMAScript5 isArray () method. If there is a across the frame, used to check whether an object is a given instance constructor GetTypeName () above is a usable workaround, but perhaps there is a more fundamental solution.

6. Review
The following should be the most urgently needed feature in JavaScript to replace some of the current responsibilities of typeof:

IsDefined () (such as object.isdefined ()): can be used as a function or as an operator
IsObject ()
GetTypeName ()
A mechanism that detects, across frameworks, whether an object is an instance of the specified constructor
It may not be necessary to have its own operator to check whether a variable has been declared.


Related articles: