Javascript--this, constructor, prototype

Source: Internet
Author: User

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:

        <script type= "Text/javascript" >            console.log (this = = window);  True            console.log (Window.alert = = = This.alert);  True            Console.log (This.parseint ("021", "ten)");  Ten        </script>        

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

        Defines a global function, Functions        foo () {            console.log (this.fruit);        }        Define a global variable equivalent to Window.fruit = "Apple";        var fruit = "Apple";        In this case, this point in the function Foo points to the Window object        //This method of invocation and Window.foo (); Is the fully equivalent of        foo ();  "Apple"        //Customize an object and point the property Foo of this object to the global function foo        var pack = {            fruit: "Orange",            Foo:foo        };        In this case, this point in function foo points to the Window.pack object        pack.foo ();//"Orange"        

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

        Defines a global function, Functions        foo () {            console.log (this.fruit);        }                Define a global variable        var fruit = "Apple";        Customizing an object        var pack = {            fruit: "Orange"        };                Equivalent to Window.foo ();        foo.apply (window);  "Apple"        //the This = = = Pack        foo.apply (Pack) in Foo at this time;    "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:

        Defines a global function that functions        foo () {            if (this = = window) {                Console.log ("This is window.");            }        }                The function foo is also an object, so you can define the properties of Foo as a function        Foo.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 function        Foo.boo ();  This is foo.                Use apply to change the point of this in the Function        foo.boo.apply (window);  This is window.
Prototype

We have used the prototype simulation classes and inheritance implementations in the first chapter. 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 person        (name) {            this.name = name;        }        Define the prototype of the person, the properties in the prototype can be referenced by custom object        Person.prototype = {            getname:function () {                return this.name;            }        }        var Zhang = new person ("Zhangsan");        Console.log (Zhang.getname ());   "Zhangsan"        
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 an array of constructors as a predefined type of JavaScript        function Array () {            //...        }                Initialize an instance of an array        var arr1 = new Array (1, +, +);        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 Array        Array.prototype.min = function () {            var min = this[0];            for (var i = 1; i < this.length; i++) {                if (This[i] < min) {                    min = this[i];                }            }            return min;        };                The Min method is called on an instance of any array        console.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 i in arr.) {Total            + = parseint (Arr[i]);        }        Console.log (total);   NaN                
The workaround is also simple:
        var arr = [1, +/--+];        var total = 0;        for (var i in arr) {            if (Arr.hasownproperty (i)) {total                + = parseint (Arr[i], ten);}        }        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, +, +);        var arr = [1, +/--+];        Console.log (Arr.constructor = = = Array); True        //equivalent to var foo = new Function ();        var Foo = function () {};        Console.log (Foo.constructor = = = Function); True        //instantiated by the constructor of an obj object        var obj = new Foo ();        Console.log (Obj.constructor = = = Foo); True                //Put the above two pieces of code together and get the following conclusion        console.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:

        function person (name) {            this.name = name;        };        Person.prototype.getName = function () {            return this.name;        };        var p = new Person ("Zhangsan");                Console.log (P.constructor = = = person);  True        console.log (Person.prototype.constructor = = person);//True        //combine the last two lines of code to get the following results        Console.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:
        function person (name) {            this.name = name;        };        Person.prototype = {            getname:function () {                return this.name;            }        };        var p = new Person ("Zhangsan");        Console.log (P.constructor = = = person);  False        console.log (Person.prototype.constructor = = = person);//False        Console.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:
        Person.prototype = new Object ({            getname:function () {                return this.name;            }        });        
and constructor always points to the constructor that created itself, so at this point Person.prototype.constructor = = = Object, which is:
        function person (name) {            this.name = name;        };        Person.prototype = {            getname:function () {                return this.name;            }        };        var p = new Person ("Zhangsan");        Console.log (P.constructor = = = Object);  True        console.log (Person.prototype.constructor = = = Object);//True        Console.log ( P.constructor.prototype.constructor = = = Object); True        
How to fix this problem? Method is also very simple, re-overwrite Person.prototype.constructor can:
        function person (name) {            this.name = name;        };        Person.prototype = new Object ({            getname:function () {                return this.name;            }        });        Person.prototype.constructor = person;        var p = new Person ("Zhangsan");        Console.log (P.constructor = = = person);  True        console.log (Person.prototype.constructor = = = person);//True        Console.log ( P.constructor.prototype.constructor = = = person); True

Javascript--this, constructor, prototype

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.