"Turn" JS cliché This,constructor, prototype

Source: Internet
Author: User

Objective

This,constructor in JavaScript, prototype, are commonplace, and it's important to understand their meaning in depth. Here, let's go over it, and warm up to know the new!

This

This represents the current object, if this is used within the global scope, refers to the current Page Object window, and if this is used in the function, the this refers to what is called based on what object the function is running at. We can also use the Apply and call two global methods to change the specific point of this in the function.

Let's look at an example that uses this in a global scope:

1 console.log ( this = = = window);  // true 2   this. alert);  // true 3   Console.log (this. parseint ("021", "ten)");  // Ten

The This in the function is determined at run time, not the function definition, as follows:

//define a global function        functionfoo () {Console.log ( This. Fruit); }        //define a global variable equivalent to Window.fruit = "Apple";        varFruit = "Apple"; //this point in the function Foo points to the Window object        //This method of invocation and Window.foo () is completely equivalent.Foo ();//"Apple"        //customize an object and point the property Foo of this object to the global function foo        varPack ={fruit:"Orange", Foo:foo}; //this point in function foo points to the Window.pack objectPack.foo ();//"Orange"

Global functions apply and call can be used to change the direction of this in the function as follows:

//define a global function        functionfoo () {Console.log ( This. Fruit); }        //define a global variable        varFruit = "Apple"; //customizing an Object        varPack ={fruit:"Orange"        }; //equivalent to Window.foo ();foo.apply (window);//"Apple"        //the This = = = Pack in fooFoo.apply (Pack);//"Orange"

Note: The function of apply and call two is the same, the only difference is that the parameter definitions of two functions are different.

Because functions are also objects in JavaScript, we can see interesting examples like this:

//define a global function        functionfoo () {if( This===window) {Console.log ("This is window."); }        }        //function Foo is also an object, so you can define the properties of Foo as a functionFoo.boo =function() {            if( This===foo) {Console.log ("This is foo."); } Else if( This===window) {Console.log ("This is window.");        }        }; //equivalent to Window.foo ();Foo ();//This is window.        //you can see the object of this in the function pointing to the calling functionFoo.boo ();//This is foo.        //use apply to change the direction of this in the functionfoo.boo.apply (window);//This is window.
Prototype

Prototype is essentially a JavaScript object.

And each function has a default prototype property. If this function is used to create a custom object in the scene, we call this function a constructor. For example, here is a simple scenario:

//constructor Function        functionPerson (name) { This. Name =name; }        //define the prototype of the person, and the properties in the prototype can be referenced by the custom objectPerson.prototype ={getName:function() {                return  This. Name; }        }        varhao=NewPerson ("Haorooms");   Console.log (Hao.getname ()); //"Haorooms"

As an analogy, we consider the data types in JavaScript-string (string), number, array, objects (object), date, and so on.

We have reason to believe that within JavaScript these types are implemented as constructors, such as:

// defines the constructor of an array as a predefined type        of JavaScript function Array () {            //  ...         }        //  Initialize an instance        of an array var New Array (1, up, down);         // However, we prefer the following syntax definitions:        var arr2 = [1, 56, 34, 12];

Many methods (such as Concat, join, push) at the same time for an array operation should also be defined in the prototype attribute. In fact, all of JavaScript's intrinsic data types have a read-only prototype property (which is understandable: because if these types of prototype properties are modified, the predefined methods disappear), but we can add our own extension methods to them.

//extend a method that gets the minimum value to the JavaScript intrinsic type arrayArray.prototype.min =function() {            varMin = This[0];  for(vari = 1; I < This. length; i++) {                if( This[I] <min) {min= This[i]; }            }            returnmin;        }; //Call the Min method on an instance of any arrayConsole.log ([1, +, 12].min ());//1

Note: Here is a trap that, when you add an extension method to the array's prototype, the extension method is also recycled when using the For-in loop array. The following code illustrates this (assuming that the Min method has been extended to the array's prototype):

var arr = [1, +/--+];         var total = 0;          for (var in arr) {            + = parseint (Arr[i], ten);        }        Console.log (total);    // NaN

The workaround is also simple:

var arr = [1, +/--+];         var total = 0;          for (var in arr) {            if  (Arr.hasownproperty (i)) {                + = parseint ( Arr[i];            }        }        Console.log (total);    // 103
Constructor

Constructor always points to the constructor that creates the current object. For example, the following:

//equivalent to var foo = new Array (1, +, +);        vararr = [1, 56, 34, 12]; Console.log (Arr.constructor= = = Array);//true        //equivalent to var foo = new Function ();        varFoo =function() { }; Console.log (Foo.constructor= = = Function);//true        //instantiating an Obj object from a constructor        varobj =NewFoo (); Console.log (Obj.constructor= = = Foo);//true        //The above two pieces of code together to get the following conclusionsConsole.log (Obj.constructor.constructor = = = Function);//true

But when constructor met prototype, something interesting happened. We know that each function has a default property of prototype, and this prototype constructor is the default point to this function. As shown in the following example:

functionPerson (name) { This. Name =name;        }; Person.prototype.getName=function() {            return  This. Name;        }; varp =NewPerson ("Haorooms"); Console.log (P.constructor= = = person);//trueConsole.log (Person.prototype.constructor = = = person);//true        //merge The last two lines of code to get the following resultsConsole.log (P.constructor.prototype.constructor = = = person);//true

When we re-defined the function's prototype (note: The difference between the above example is not modified, but overwritten), constructor's behavior is a bit odd, as in the following example:

functionPerson (name) { This. Name =name;        }; Person.prototype={getName:function() {                return  This. Name;        }        }; varp =NewPerson ("Haorooms"); Console.log (P.constructor= = = person);//falseConsole.log (Person.prototype.constructor = = = person);//falseConsole.log (P.constructor.prototype.constructor = = = person);//false

Why is it? It turns out that when overwriting person.prototype, it is equivalent to doing the following code:

New Object ({            function() {                returnthis. Name;            }        });

and constructor always points to the constructor that created itself, so at this point Person.prototype.constructor = = = Object, which is:

functionPerson (name) { This. Name =name;        }; Person.prototype={getName:function() {                return  This. Name;        }        }; varp =NewPerson ("Haorooms"); Console.log (P.constructor= = = Object);//trueConsole.log (Person.prototype.constructor = = = Object);//trueConsole.log (P.constructor.prototype.constructor = = = Object);//true

How to fix this problem? Method is also very simple, re-overwrite Person.prototype.constructor can:

functionPerson (name) { This. Name =name;        }; Person.prototype={getName:function() {                return  This. Name;        }        }; Person.prototype.constructor=Person ; varp =NewPerson ("Haorooms"); Console.log (P.constructor= = = person);//trueConsole.log (Person.prototype.constructor = = = person);//trueConsole.log (P.constructor.prototype.constructor = = = person);//true

You can also write this:

function Person (name) {            this. Name = name;        };          = {          Constructor:person,// Specify constructor            function() {                 returnthis. Name;            }        ;

Transferred from: Http://www.haorooms.com/post/js_constructor_pro

"Turn" JS cliché This,constructor, prototype

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.