Talk about my deep understanding of typeof and instanceof in JavaScript _javascript skills

Source: Internet
Author: User

This is mainly about the type judgment function of JavaScript typeof and judging the use and attention of the prototype instanceof of the constructor.

typeof

Let's talk about typeof first. The first thing to note is that the TypeOf method returns a String that represents the type of data.

TypeOf is a unary operation, which can be any type of operation before it is placed in one op-count.

The return value is a string that describes the type of the operand. typeof generally can only return the following results:
number,boolean,string,function,object,undefined. We can use TypeOf to get the existence of a variable, such as if (typeof a!= "undefined") {alert ("OK")}, and not to use if (a) because if a does not exist (not declared) there will be an error, for the Array,null Such special objects use TypeOf to return object, which is the limitation of TypeOf.

Grammar explanation

Let's look at the values of each data type corresponding to typeof:

Data Type Type
Undefined "Undefined"
Null "Object"
Boolean value "Boolean"
Numerical "Number"
String "String"
Symbol (ECMAScript 6 new) "Symbol"
Host objects (provided by the JS environment, such as browsers) Implementation-dependent
Function object "Function"
Any other object "Object"

Take a look at specific examples:

Numbers typeof of Panax Notoginseng = = ' number ';
typeof 3.14 = = = ' number ';
typeof MATH.LN2 = = = ' number ';
typeof Infinity = = = ' number '; typeof NaN = = ' number '; Although Nan is an abbreviation for "Not-a-number", it means "not a number" (1) = = = ' typeof ';
Don't use that!
Strings typeof "" = = = ' String ';
typeof "Bla" = = = ' String '; typeof (typeof 1) = = ' String '; typeof return is definitely a string typeof string ("abc") = = ' String ';
Don't use that!
Booleans typeof true = = ' Boolean ';
typeof false = = = ' Boolean '; typeof Boolean (true) = = ' Boolean ';
Don't use that!
Symbols typeof symbol () = = = ' symbol ';
typeof symbol (' foo ') = = ' symbol ';
typeof Symbol.iterator = = = ' Symbol ';
Undefined typeof Undefined = = ' Undefined '; typeof BlaBla = = ' undefined ';
An undefined variable, or a variable that has not been assigned an initial value//Objects typeof {A:1} = = = = ' object ';
Use the Array.isarray or Object.prototype.toString.call method to differentiate the array types from the basic objects typeof [1, 2, 4] = = ' object ';
typeof new Date () = = ' object ';
The following is easy to confuse, do not use this!
typeof New Boolean (true) = = = ' object ';
typeof new Number (1) = = = ' object '; typeof New STring ("abc") = = = ' object ';
Functions typeof function () {} = = = ' function '; typeof Math.sin = = ' function ';

We will find a problem, that is, typeof to determine that the data type is not actually accurate. For example, array, regular, date, object typeof return value is object, this will cause some errors.

Therefore, on the basis of TypeOf judgment type, we also need to use Object.prototype.toString method to judge the data type further.

Let's take a look at the difference between the ToString method and the TypeOf method return value in the case of the same data type:

Data toString typeof
"Foo" String String
New String ("foo") String Object
New Number (1.2) Number Object
True Boolean Boolean
New Boolean (True) Boolean Object
New Date () Date Object
New Error () Error Object
New Array (1, 2, 3) Array Object
/abc/g Regexp Object
New RegExp ("Meow") Regexp Object

You can see that by using the ToString method, you can correctly distinguish the types of array, Error, REGEXP, date, and so on.

So we generally use this method to validate data types.

Real problem detection

But now that we're talking about typeof, here's a list of questions to see if you really know how to use typeof.

First question:

var y = 1, x = y = typeof x;
X

Second question:

(function f (f) {return
typeof F ();
}) (function () {return 1;});

Third question:

var foo = {
bar:function () {return this.baz;},
baz:1
};
(function () {return
typeof arguments[0] ();
}) (Foo.bar);

Question Fourth:

var foo = {
bar:function () {return this.baz;},
baz:1
}
typeof (F = foo.bar) ();

Question Fifth:

var F = (function f () {return ' 1 ';}, function g () {return 2;}) ();
typeof F;

Question sixth:

var x = 1;
if (function f () {}) {
x + = typeof f;
}
X

Question seventh:

(function (foo) {return
typeof foo.bar;
}) ({foo: {bar:1}});

The answers to the seven questions are as follows:

"Undefined", "number", "Undefined", "undefined", "number", "1undefined", "undefined"

What's the right way to do it? Isn't that a big puzzle? These questions are all typeof, but look at the basics of JavaScript. Below we come to one by one detailed.

First question:

var y = 1, x = y = typeof x;
x;//"Undefined"

The expression is from right to left, x because of the variable elevation, the type is not NULL, but undefined, so x=y= "undefined".

Variable elevation I have mentioned this in this article and can look at it.

Second question:

(function f (f) {return
typeof F ();//"number"
}) (function () {return 1;});

The argument passed is F, which is function () {return 1;} This function. After executing with f (), the result is 1, so typeof 1 returns "number". This problem is very simple, mainly to distinguish F and f ().

Third question:

var foo = {
bar:function () {return this.baz;},
baz:1
};
(function () {return
typeof arguments[0] ();//"Undefined"
}) (Foo.bar);

This topic examines the point of this. This always points to the context at which the function executes, not when it is defined (the ES6 arrow function does not count). When arguments executes, this already points to the Window object. So it's "undefined". Students who are unfamiliar with this can take a look at this article: a deep understanding of this, and the students interested in the arrow function just mentioned can take a look at the ES6 arrow function.

Question Fourth:

var foo = {
bar:function () {return this.baz;},
baz:1
}
typeof (F = foo.bar) ();//undefined

If the above problem is right, then the problem should not be wrong, the same is the point of this.

Question Fifth:

var F = (function f () {return ' 1 ';}, function g () {return 2;}) ();
typeof f;//"Number"

This one is easier to get wrong because I've never encountered a group selector for JavaScript before I met this problem. What is called a grouping selector? One example would make it clear:

var a = (1,2,3);
document.write (a);//3, whichever is the last.

So the title above will return 2,typeof 2 of course "number".

Question sixth:

var x = 1;
if (function f () {}) {
x + = typeof f;
}
x;//"1undefined"

This is a problem with the JavaScript language specification, which adds a function declaration to the conditional judgment. The declaration statement itself is not wrong and returns true, but the JavaScript engine cannot find the function while searching. So the result is "1undefined".

Question seventh:

(function (foo) {return
typeof foo.bar;
}) ({foo: {bar:1}});

This question is actually an examination of the forestall degree of the topic. The formal parameter foo is pointing to the whole of {foo: {bar:1}}}. I'm sure that's a clear idea.

All right. The above questions are all very good resources oh.

instanceof

Then let's talk about the Instanceof method. The instanceof operator can be used to determine whether a constructor's prototype attribute exists on another prototype chain to be instrumented.

Instanceof is used to determine whether a variable is an instance of an object, such as the Var a=new array (); alert (a instanceof array); Returns True, while alert (a Instanceof object) returns True, because the Array is a subclass of Object. Another example: function Test () {};var a=new test (); alert (a instanceof test) returns

When it comes to instanceof, we're going to insert one more question, which is the arguments of the function, and we all probably think that arguments is an array, but if you use instaceof to test, you'll find that arguments is not an array object, though it looks like it.

If you are not familiar with the prototype, you can look at the deep understanding of the prototype.

Let's take a look at Instanceof's example:

Define constructor function function
C () {} 
function D () {} 
var o = new C ();
True because Object.getprototypeof (o) = = = C.prototype
o instanceof C; 
False because D.prototype is not on the prototype chain o
instanceof D; 
o instanceof Object; True because Object.prototype.isPrototypeOf (o) returns true
c.prototype instanceof Object//True, ditto
c.prototype = {};
var O2 = new C ();
O2 instanceof C; True
o instanceof C;//False,c.prototype points to an empty object that is not on the prototype chain of O.
D.prototype = new C (); Inherit
var O3 = new D ();
O3 instanceof D; True
O3 instanceof C;//True

But here's a question we need to be aware of:

function f () {return F;}
document.write (new F () instanceof f);//false
function g () {}
document.write (new G () instanceof g);//true

Why did the first one return false? Because the stereotype of the constructor is overwritten, we can look at the difference between new F and new G:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.