Home >Web Front-end >JS Tutorial >Introduction to the difference between typeof and instanceof in JavaScript (code example)
This article brings you an introduction to the difference between typeof and instanceof in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
typeof and instanceof in JavaScript are often used to determine whether a variable is empty or what type it is. But there are still differences between them:
typeof
typeof is a unary operation, placed before an operand, and the operand can be of any type.
The return value is a string that describes the type of the operand. (The typeof operator returns a string used to represent the data type of the expression.)
typeof is actually an instance of determining what type the parameter is. For one parameter,
typeof can generally only return The following results: "number", "string", "boolean", "object", "function" and "undefined".
The operand is a number typeof(x) = "number"
String typeof(x) = "string"
Boolean value typeof(x) = "boolean"
Object, array and null typeof(x) = "object"
Function typeof(x) = "function"
console.log(typeof (123));//typeof(123)返回"number" console.log(typeof ("123"));//typeof("123")返回"string" var param1 = "string"; var param2 = new Object(); var param3 = 10; console.log(typeof(param1)+"\n"+typeof(param2)+"\n"+typeof(param3)); // string object number
We can use typeof to get whether a variable exists, such as if(typeof a!="undefined"){alert("ok")}, do not use if(a) because if a does not exist (undeclared), an error will occur, for special objects such as Array and Null Using typeof always returns object. This is the limitation of typeof.
Arrays are often used in js, such as multiple inputs with the same name. If they are dynamically generated, you need to determine whether they are arrays when submitting.
if(document.mylist.length != "undefined" ) {} //这个用法有误. 正确的是 `if( typeof(document.mylist.length) != "undefined" ) {}` 或 `if( !isNaN(document.mylist.length) ) {}`
The operands of typeof are not Definition, the return value is "undefined".
In JavaScript, you will use the typeof operator to determine the type of a variable. When using the typeof operator, a problem will arise when using a reference type to store the value. Regardless of the reference No matter what type of object it is, it returns "object". This requires instanceof to detect whether an object is an instance of another object.
instanceof
The instanceof operator is used to test whether an object has a constructor's prototype attribute in its prototype chain.
Syntax: object instanceof constructor
Parameters: object (object to be detected.) constructor (a constructor)
Description: instanceof operator is used to detect whether constructor.prototype exists in the parameter object on the prototype chain.
instance: instance, example
a instanceof b?alert("true"):alert("false"); //a is an instance of b? True: False
instanceof is used to determine whether a variable is an instance of an object,
如 :var a=new Array(); alert(a instanceof Array); // true, 同时 alert(a instanceof Object) //也会返回 true; 这是因为 Array 是 object 的子类。 再如:function test(){}; var a=new test(); alert(a instanceof test) 会返回true alert(a==b); //flase
Case:
另外,更重的一点是 `instanceof` 可以在继承关系中用来判断一个实例是否属于它的父类型。 例如: function Foo(){} Foo.prototype = new Aoo();//JavaScript 原型继承 var foo = new Foo(); console.log(foo instanceof Foo)//true console.log(foo instanceof Aoo)//true 上面的代码中是判断了一层继承关系中的父类,在多层继承关系中,instanceof 运算符同样适用。 又如: console.log(Object instanceof Object);//true console.log(Function instanceof Function);//true console.log(Number instanceof Number);//false console.log(String instanceof String);//false console.log(Function instanceof Object);//true console.log(Foo instanceof Function);//true console.log(Foo instanceof Foo);//false
// 定义构造函数 function C(){} function D(){} var o = new C(); // true,因为 Object.getPrototypeOf(o) === C.prototype o instanceof C; // false,因为 D.prototype不在o的原型链上 o instanceof D; o instanceof Object; // true,因为Object.prototype.isPrototypeOf(o)返回true C.prototype instanceof Object // true,同上 C.prototype = {}; var o2 = new C(); o2 instanceof C; // true o instanceof C; // false,C.prototype指向了一个空对象,这个空对象不在o的原型链上. D.prototype = new C(); // 继承 var o3 = new D(); o3 instanceof D; // true o3 instanceof C; // true
Speaking of instanceof we have to insert one more question, which is function Arguments, we all may think that arguments is an Array, but if you use instanceof to test, you will find that arguments is not an Array object, although it looks very similar.
Also:
Test var a=new Array();if (a instanceof Object) alert('Y');else alert('N');
Got 'Y'
But if (window instanceof Object) alert('Y');else alert('N');
got 'N'
So, The object tested by instanceof here refers to the object in js syntax, not the dom model object.
There will be some differences when using typeof
alert(typeof(window)) will get object
It should be noted that if the expression obj instanceof Foo returns true, it does not This means that the expression will always return true, because the value of the Foo.prototype attribute may change, and the changed value may not exist on the prototype chain of obj. In this case, the value of the original expression will become false. In another case, the value of the original expression will also change, that is, the prototype chain of the object obj is changed. Although in the current ES specification, we can only read the prototype of the object but cannot change it, but with the help of non- Standard __proto__ magic properties are achievable. For example, after executing obj.__proto__ = {}, obj instanceof Foo will return false.
Example: Show that String objects and Date objects both belong to the Object type
The following code uses instanceof to prove that: String and Date objects also belong to the Object type.
例子: 表明String对象和Date对象都属于Object类型 下面的代码使用了instanceof来证明:String和Date对象同时也属于Object类型。 var simpleStr = "This is a simple string"; var myString = new String(); var newStr = new String("String created with constructor"); var myDate = new Date(); var myObj = {}; simpleStr instanceof String; // returns false, 检查原型链会找到 undefined myString instanceof String; // returns true newStr instanceof String; // returns true myString instanceof Object; // returns true myObj instanceof Object; // returns true, despite an undefined prototype ({}) instanceof Object; // returns true, 同上 myString instanceof Date; // returns false myDate instanceof Date; // returns true myDate instanceof Object; // returns true myDate instanceof String; // returns false
The above is the detailed content of Introduction to the difference between typeof and instanceof in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!