


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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor
