JavaScript type detection

Source: Internet
Author: User
Tags object object

JavaScript type detection mainly includes the following methods:

typeof
instanceof
Object.prototype.toString
Constructor
Duck type

First, typeof method

typeof can detect the data type of a given variable, and using the TypeOf operator on a value may return one of the following strings:

"Undefined" If this value is undefined

"Boolean" If this value is a Boolean value

"String" If this value is a string

"Number" If this value is numeric

"Object" If this value is an object or null

"Function" If this value is

For example:

function A () {}typeof 100;//numbertypeof true;//booleantypeof "str";//stringtypeof undefined;//undefinedtypeof null;/ /objecttypeof nan;//numbertypeof function;//functiontypeof object;//functiontypeof new Object ();//objecttypeof [up] ;//objecttypeof a;//function

A null value represents an empty object pointer, so a value that detects typeof null returns "Object"

Second, instanceof method

Syntax: Result=variable instanceof Constructor

If the variable is an instance of a given reference type, then the instanceof operator returns true

function person () {}function-Student () {}student.prototype=new person (); Student.prototype.constructor=student;var bosn=new Student (); var one=new person (); Bosn instanceof Student;//trueone instanceof person;//trueone instanceof student;//falsebosn instanceof person;//truevar colors=["Red", "Blue", "green"] ; Console.log (colors instanceof Array);//truevar pattern=/[ac]ont/gi;console.log (Pattern instanceof REGEXP);// Truevar date=new Date (); Console.log (date instanceof date);//true

The value of all reference types is an instance of object

Iii. Methods of Object.prototype.toString

Object.prototype.toString.apply ([]); = = = "[Object Array]"; Object.prototype.toString.apply (function () {}); = = = "[Object Function]"; Object.prototype.toString.apply (null); = = = "[Object Null]" Object.prototype.toString.apply (undefined); = = = "[Object Undefined]" Object.prototype.toString.apply (new Date ());//[object date]object.prototype.tostring.apply (New String ("str"));//[object string]object.prototype.tostring.apply ("str");//[object string] Object.prototype.toString.apply (123);//[object number]
Object.prototype.toString.call and Object.prototype.toString.apply are the same.

To determine the native reference type:
function type

FUNCTION fn () {Console.log ("Test");} Object.prototype.toString.call (FN);//"[Object Function]"

Date type

var date = new Date (); Object.prototype.toString.call (date);//"[Object Date]"

Array type

var arr = [1,2,3];object.prototype.tostring.call (arr);//"[Object Array]"

Regular expressions

var reg =/[hbc]at/gi;object.prototype.tostring.call (reg);//"[Object Array]"

Custom Types

function person (name, age) {this.name = Name;this.age = age;} var person = new Person ("Rose", Object.prototype.toString.call); "[Object Object]"

To determine the native JSON object:

var Isnativejson = window. JSON && Object.prototype.toString.call (JSON); Console.log (Isnativejson);//The output is "[Object JSON]" indicating that the JSON is native, otherwise not;

Iv. Methods of Construct

var test=new Array (); Console.log (Test.constructor==array);//truefunction A () {};var a1=new A (); Console.log ( A1.CONSTRUCTOR==A);//trueconsole.log (a.prototype.constructor==a);//true

Instance:

The constructor function Foo (y) {  ///constructor will create the object in a specific pattern: the object being created will have the "Y" property  this.y = y;} "Foo.prototype" holds the prototype reference for the new object//So we can use it to define inheritance and shared properties or methods//So, as in the example above, we have the following code://Inheritance Property "x" foo.prototype.x = 10; The inheritance Method "calculate" Foo.prototype.calculate = function (z) {   return this.x + This.y + z;};  Use Foo mode to create "B" and "C" var b = new Foo (+); var c = new Foo (+);  Method of invoking Inheritance B.calculate (30); 60c.calculate (40); 80//let's see if the expected properties are used Console.log (  b.__proto__ = = = Foo.prototype,//true  c.__proto__ = = = Foo.prototype,// True  //"Foo.prototype" automatically creates a special attribute "constructor"//  the constructor of a to itself//  instance "B" and "C" can be found by authorization and used to detect its own constructor  B.constructor = = = Foo,//true  c.constructor = = = Foo,//true  Foo.prototype.constructor = = = Foo//True
   b.calculate = = = B.__proto__.calculate,//true  b.__proto__.calculate = = = Foo.prototype.calculate//TRUE);

  

V. Duck Type method

In program design, Duck type (English: Duck typing) is a style of dynamic type. In this style, an object's valid semantics are not inherited from a particular class or implemented by a particular interface, but rather by the collection of current methods and properties. The name of the concept derives from the duck test presented by James Whitcomb Riley, which can be described as "duck test":

"When you see a bird walking like a duck, swimming like a duck and barking like a duck, the bird can be called a duck." ”
In duck type, the focus is not on the type of the object itself, but how it is used.

JavaScript type detection

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.