JavaScript instanceof operator

Source: Internet
Author: User
Tags string

JavaScript instanceof operator
The instanceof operator is used to compare the constructors of the two operands. It is only meaningful to compare a custom object.
If used to compare built-in types, it will be as useful as the TypeOf operator.
Comparing Custom Objects
function Foo () {}
function Bar () {}
Bar.prototype = new Foo ();
New Bar () instanceof Bar; True
New Bar () instanceof Foo; True
If you only set Bar.prototype as a function of Foo, not an instance of the Foo constructor
Bar.prototype = Foo;
New Bar () instanceof Foo; False
instanceof Compare built-in types
New string (' foo ') instanceof string; True
New String (' foo ') instanceof Object; True
' foo ' instanceof String; False
' foo ' instanceof Object; False
It is important to note that instanceof is used to compare objects belonging to different JavaScript contexts (for example, different document structures in browsers),
Because their constructors are not the same object.
Conclusion
The instanceof operator should be used only to compare custom objects from the same JavaScript context.
As with the typeof operator, any other usage should be avoided.



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.