JS type judgment and duck type discrimination

Source: Internet
Author: User

Directory

instanceof

Constructor

Constructor name

Duck Type Distinguishing type

Three types of Detection objects: instanceof, constructor, constructor name

Use the following:

1) instanceof
instanceof Array); true Console.log ([instanceof  Object); true

Although the constructor is the unique identity of the prototype, the right operand of the instanceof operator is a constructor that instanceof the inheritance of the object during the actual calculation, rather than the constructor that detects the object when it was created, but uses the constructor as the intermediary

Of course, you can also use isprototypeof to determine whether an object exists in the prototype chain of another object and does not use a constructor as a mediation

var New Array (); Console.log (Array.prototype.isPrototypeOf (A1)); true Console.log (Array.prototype.isPrototypeOf ([+])); true

Note: When multiple execution contexts (for example, when there are different frames), the instanceof uses a limited

2) constructor

Each JavaScript function can be used as a constructor, and the call constructor needs to use the prototype property, so each JavaScript function automatically has the prototype property, which is an object that contains a Contructor property , the constructor property value is a function object.

That is, the function var F = function () {}; f.prototype.constructor===f

The diagram is as follows:

eg

var function (){}; var p = f.prototype; var c = p.constructor;console.log (p); Console.log (c); Console.log (c= = =F);
Object {}function () {}true

Thus the constructor of object inheritance refer to their constructors

eg

var New F (); Console.log (O.constructor===f);


True

var New Array (); Console.log (a.constructor= = =array);
Output
True

function Typediscern (x) {  switch(x.constructor) {    casereturn "number: "+x;      Case return "String:" +x;      Case return "Array:" +x;        }} Console.log ([Typediscern]); Console.log (Typediscern ("abc")); Console.log ( Typediscern (5));
Output
Array:string:abcnumber:5

Note: The same instanceof cannot be used in multiple contexts, and not all objects contain constructor properties

eg

Defining the Person class

functionPerson (name) { This. name=name;  This. getname=function()           {              return  This. Name;     }   }; varWish=NewPerson (' JS '); Console.log (Wish.constructor==Person );  Console.log (Person.prototype); Console.log (Person.constructor); Console.log (Wish.getname ());

OutputtruePerson {}functionFunction () {[native code]}JS

Customizing prototype for Person

functionPerson (name) { This. name=name;  This. getname=function()           {              return  This. Name;   }   }; Person.prototype={toString:function(){        return  This. Name;  }}; varWish=NewPerson (' JS '); Console.log (Wish.constructor==Person );  Console.log (Person.prototype); Console.log (Person.constructor); Console.log (Wish.getname ()); Console.log (wish.tostring ());

OutputfalseObject {toString:function}functionFunction () {[native code]}JSJS

The newly defined prototype object does not contain the constructor property, so the instance of person does not contain the constructor attribute

Workaround: Add a construction method to the prototype that can be displayed

Person.prototype={    constructor= Person,    function() {        return  this. Name;}    ;
Constructor name

There are no execution context issues for intanceof and constructor, and the array constructor in one window is unequal to the array constructor in another window, but the constructors have the same name, but not every function has a name

function () {    ifin this) {        returnthis. Name;    }     returnthis. Name=. toString (). Match (/function\s* ([^ (]*)/);} function test1 () {}console.log (Test1.getname ());

Output: Test1

Duck Type Distinguishing type

Focus on what the object can do, not what the object's class is

James Whitcomb Riley A duck, a bird that walks, swims, and quack like a duck.

The main objects include walk (), swim (), bike (), which can be passed as a parameter to the three methods.

A function implemented using duck-type argument:

functionQuackimplements (o/*,...*/){     for(varI=1; i<arguments.length;i++){        vararg=Arguments[i]; Switch(typeofArg) {             Case' String ':                if(typeofo[arg]!== "function")                    return false; Continue;  Case' function ': Arg=Arg.prototype;  Case' Object ':                 for(varMinchArg) {                    if(typeofarg[m]!== "function")Continue; if(typeofo[m]!== "function")return false; }        }    }    return true;}

Direct check naming method for strings

If the object checks for a method with the same name

Whether there is the same method in the prototype object for the function check constructor

Many of the functions in JavaScript do not type-detect objects just to be concerned about what these objects can do

The prototype of Eg:array uses the duck type, arguments is a pseudo-array

(function  () {     var arr = Array.prototype.slice.apply (arguments);        Console.log (arr);}) (1, 2, 3);

Output: [1, 2, 3]

var arr = Array.prototype.slice.apply ({0:1, 1:2, 2:3, Length:3 }); Console.log (arr);//output: [1, 2, 3 ]

The use of duck type can enlarge the scope of the object

Eg: a push method that lets a normal object have an array

Function.prototype.unCurrying =function () {    varf = This; return function () {        varA =arguments; returnF.apply (A[0], [].slice.call (A, 1)); };}; Function.prototype.unCurrying=function () {    return  This. Call.bind ( This);};varPush =Array.prototype.push.unCurrying (), obj={};p ush (obj,' First ', ' both '); Console.log (obj); Console.log ("Length:" +obj.length)

Output:

Object{0: "First", 1: "Length:2",}length:2

Reference: JavaScript authoritative guide

Http://www.cnblogs.com/pigtail/p/3450852.html

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.