Home  >  Article  >  Web Front-end  >  Discussion on the use of typeof and instanceof operators in JavaScript_Basic knowledge

Discussion on the use of typeof and instanceof operators in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:33:321118browse

When writing JavaScript code, the two operators typeof and instanceof are used from time to time and are must-use. but! It is always difficult to get the desired results directly when using them. It is generally said that "these two operators are perhaps the biggest design flaw in JavaScript, because it is almost impossible to get the desired results from them"
typeof
Explanation: typeof returns a string of the data type of an expression, and the return result is the basic data type of js, including number, boolean, string, object, undefined, function.
Judging from the description, there seems to be no problem.

The following code writes a numerical variable, and the result after typeof is "number".

Copy code The code is as follows:

var a = 1;
console.log( typeof(a)); //=>number

If you use the constructor new of type Number to create a variable, the result after typeof is "object".
Copy code The code is as follows:

var a = new Number(1);
console.log(typeof(a)); //=>object

The above two output results seem to have no problem, which seems to be a matter of course from the book. Because javascript is designed this way.

But! The problem is that since typeof is called, it should accurately return the type of a variable, whether it is created directly with a value or with a type constructor, otherwise! What else should I use you for?
So for:
Copy the code The code is as follows:

var a = 1;
var b = new Number(1);

Accurately speaking, the types of a and b variables should be Number to get the desired result.
The accurate type information is stored in the value of the variable's internal property [[Class]], which is obtained by using the method toString defined on Object.prototype.

Get type information:
Copy code The code is as follows:

var a = 1;
var b = new Number(1);
console.log(Object.prototype.toString.call(a));
console.log(Object.prototype.toString.call(b ));

Output:
Copy code The code is as follows:

[object Number]
[object Number]

Isn’t it already very straightforward? Let’s do a little processing and get the direct result:
Copy code The code is as follows:

var a = 1;
var b = new Number(1);
console.log( Object.prototype.toString.call(a).slice(8,-1));
console.log(Object.prototype.toString.call(b).slice(8,-1));

Output:
Number
Number
This is the desired result.
For better use, we encapsulate a method to determine whether a variable is of a certain type:
Copy code The code is as follows:

function is(obj,type) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}

I have defined some variables and tested them. Let’s take a look at their typeof output first:
Copy code The code is as follows:

var a1=1;
var a2=Number(1 );
var b1="hello";
var b2=new String("hello");
var c1=[1,2,3];
var c2=new Array(1 ,2,3);
console.log("a1's typeof:" typeof(a1));
console.log("a2's typeof:" typeof(a2));
console.log(" b1's typeof:" typeof(b1));
console.log("b2's typeof:" typeof(b2));
console.log("c1's typeof:" typeof(c1));
console .log("c2's typeof:" typeof(c2));
Output:
a1's typeof:number
a2's typeof:object
b1's typeof:string
b2's typeof:object
c1's typeof:object
c2's typeof:object

使用する新しく作成した関数は次のとおりです:
コードをコピーします コードは次のとおりです:

console.log("a1 は番号:" is(a1,"Number"));
console.log("a2 は番号:" is(a2,"Number")); .log( "b1 は文字列です:" is(b1,"String"));
console.log("b2 は文字列です:" is(b2,"String")); c1 は配列 :" is(c1,"Array"));
console.log("c2 は配列:" is(c2,"Array"));
出力:
a1 は数値: true
a2 は Number:true
b1 は String:true
b2 は String:true
c1 は Array:true
c2 は Array:true


注: typeof 実際の用途は、変数が定義されているか、値が割り当てられているかを検出することです。

instanceof
説明: オブジェクトが特定のデータ型であるかどうか、または変数がオブジェクトのインスタンスであるかどうかを判断します。 instanceof 演算子も、2 つの組み込み型変数の比較に使用される場合には無力であり、結果にも満足できません。


console.log("abc"instanceof String ); // false
console.log("abc" オブジェクトのインスタンス); // 偽
console.log(new String("abc") インスタンスオブ String); // true
console.log( new String( "abc")instanceof Object); // true


カスタム オブジェクトを比較する場合にのみ関係を正確に反映します。


コードをコピーします コードは次のとおりです。
function Person() {}
function Man( ) {}
Man.prototype = new Person();
console.log(new Man()instanceofMan) // true
console.log(new Man()instanceofMan); ; // 真

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