Home  >  Article  >  Web Front-end  >  Detailed analysis of the usage and difference between instanceof and typeof operators in JavaScript_javascript skills

Detailed analysis of the usage and difference between instanceof and typeof operators in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:14:131153browse

Instanceof and typeof in JavaScript are often used to determine the type of a variable (instance), but their use is still different:

typeof operator
returns a string representing the data type of the expression.

typeof expression ;

The

expression parameter is any expression for which type information needs to be found.

Explanation
typeof is a unary operator, placed before an operand.

The typeof operator returns type information as a string. There are six possible return values ​​of typeof: "number", "string", "boolean", "object", "function", and "undefined."

(ECMAScript has 5 primitive types, namely Undefined, Null, Boolean, Number and String.)

Note:

1. We mentioned the five primitive types of ECMAScript above. When using the typeof operator, we need to specifically distinguish the difference between "object type" and "object value" (literal value). For example, the Boolean object is a reference type of the Boolean primitive type, and true and false are the two possible object values ​​of the Boolean object. We can think of ECMAScript's predefined objects (as opposed to classes in other languages) as encapsulation (or wrapper) of primitive values ​​of the corresponding type. All predefined objects of ECMAScript inherit from the Object object. Therefore, the following situation exists:

Copy code The code is as follows:

 var testvar= new Number(68 );
alert(typeof testvar); //Output "object"
testvar= 68;
alert(typeof testvar); //Output "number"

Another example :
Copy code The code is as follows:

function Person(){}
document. write ("
typeof(Person):" typeof(Person)); //function
var person = new Person();
document.write ("
typeof(person): " typeof(person)); //object

注意:从传统意义上来说,ECMAScript 并不真正具有类。事实上,除了说明不存在类,在 ECMA-262 中根本没有出现“类”这个词。ECMAScript 定义了“对象定义”,逻辑上等价于其他程序设计语言中的类。

另外:这些预定义对象覆盖了Object 对象的 ValueOf() 方法,返回其原始值。而这些对象的所有属性和方法都可应用于相应类型的原始值上,因为它们是伪对象。

2、typeof 运算符对于 null 值会返回 "Object"。这实际上是 JavaScript 最初实现中的一个错误,然后被 ECMAScript 沿用了。现在,null 被认为是对象的占位符,从而解释了这一矛盾,但从技术上来说,它仍然是原始值。

提示:

1、值 undefined 并不同于未定义的值。但是,typeof 运算符并不真正区分这两种值。考虑下面的代码:

var oTemp;
alert(typeof oTemp);  //输出 "undefined"
alert(typeof oTemp2);  //输出 "undefined"

前面的代码对两个变量输出的都是 "undefined",即使只有变量 oTemp2 从未被声明过。如果对 oTemp2 使用除 typeof 之外的其他运算符的话,会引起错误,因为其他运算符只能用于已声明的变量上。

2、当函数无明确返回值时,返回的也是值 "undefined",如下所示:

function testFunc() {}
alert(testFunc() == undefined);  //输出 "true"3、类型Null,它只有一个专用值 null,即它的字面量。值 undefined 实际上是从值 null 派生来的,因此 ECMAScript 把它们定义为相等的。

alert(null == undefined);  //输出 "true"
尽管这两个值相等,但它们的含义不同:

undefined 是声明了变量但未对其初始化时赋予该变量的值 或 未声明过的变量(只能用于typeof,但作为赋值目标时编译器会自动将其声明为全局变量)。

null 则用于表示尚未存在的对象(即对象为空,或对象找不到)。如果函数或方法要返回的是对象,那么找不到该对象时,返回的通常是 null。

3、我们可以使用 typeof 来获取一个变量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 因为如果 a 不存在(未声明)则会出错。

对于 Array,Null 等特殊对象使用 typeof 一律返回 object,这正是 typeof 的局限性。如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。


instanceof 运算符
在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。ECMAScript 引入了另一个 Java 运算符 instanceof 来解决这个问题。

instanceof 运算符与 typeof 运算符相似,用于识别正在处理的对象的类型。与 typeof 方法不同的是,instanceof 方法要求开发者明确地确认对象为某特定类型。例如:

var oStringObject = new String("hello world");
alert(oStringObject instanceof String); //输出 "true"
这段代码问的是“变量 oStringObject 是否为 String 对象的实例?”oStringObject 的确是 String 对象的实例,因此结果是 "true"。尽管不像 typeof 方法那样灵活,但是在 typeof 方法返回 "object" 的情况下,instanceof 方法还是很有用的。

instanceof运算符

是一个二元运算符。返回一个 Boolean 值,指出对象是否是特定类的一个实例。

expression  instanceof class

参数

 expression  必选项。任意对象表达式。

 class  必选项。任意已定义的对象类。

说明
如果 object 是 class 的一个实例,则 instanceof 运算符返回 true 。如果 object不是指定类的一个实例,或者 object 是 null ,则返回 false 。

用于判断一个变量是否某个对象的实例,

如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。

注意:

关于function 的 arguments,我们大家也许都认为 arguments 是一个 Array,但如果使用 instaceof 去测试会发现 arguments 不是一个 Array 对象,尽管看起来很像。

此外还有类似的情况,例如:

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 at this time: alert(typeof(window)) will get object

Extension: What is the principle of instanceof operator in JavaScript?

When learning js, I learned that when judging whether an instance in js belongs to a certain type, you can use the instanceof operator, such as function Person(){}

var person = new Person(); alert(person instanceof Person);//return true

So what judgment was made when executing the instanceof operation and returned true/false?

Could it be that the result is obtained by judging whether the references of Person.prototype and person's internal pointer [[prototype]] are the same?

In fact, if the prototype object pointed to by the prototype attribute of the constructor can be found in the "prototype object chain" of the instance, true will be returned.

The prototype is not an attribute of the instance at all (or the prototype attribute of the instance is undefined), but an attribute in its prototype object. If it is tampered with, this judgment method cannot return correctly.

In addition, can we directly judge person.constructor == Person to obtain the desired result?

Let’s do a test, the following JavaScript code:

Copy the code The code is as follows:

function Person(name,sex){this.name=name;this.sex=sex;}
document.write ("
typeof Person:" typeof Person);
document.write ("< ;br>typeof Person.prototype:" typeof Person.prototype);
document.write ("
typeof Person.constructor:" typeof Person.constructor);

var person = new Person();
document.write ("

var person = new Person();");
document.write ("
typeof person:" typeof person);
document.write ("
typeof person.prototype:" typeof person.prototype);
document.write ("
typeof person.constructor:" typeof person.constructor);

document.write ("

Function.constructor:" Function.constructor);
document.write ("

Function.prototype:" Function.prototype );

document.write ("

Person.constructor:" Person.constructor);
document.write ("

Person.prototype:" Person.prototype );


document.write ("

person.constructor:" person.constructor);
document.write ("

person.prototype:" person.prototype);

The output is as follows:

typeof Person:function
typeof Person.prototype:object
typeof Person.constructor:function

var person = new Person();
typeof person:object
typeof person.prototype:undefined
typeof person.constructor:function


Function.constructor:function Function() { [native code] }
Function.prototype:function Empty() {}

Person.constructor:function Function() { [native code] }
Person.prototype:[object Object]

person.constructor:function Person(name,sex){this.name=name;this.sex=sex;}
person.prototype:undefined

Similar to Function, Number() is the constructor of Number object. Number() is used to convert its parameters into number type and return the conversion result (if it cannot be converted, it returns NaN).

Constructor is less commonly used in JavaScript. variable.constructor returns a string representation of the constructor of its object class.

Then when judging the data type in JavaScript, we can use the following method to get its detailed data type:

if((typeof a=="object") && (a.constructor==Array)){

}

Note: constructor can only judge existing variables, while typeof can judge undeclared variables or empty objects (return undefined).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn