On functions, this and prototype _javascript techniques in JavaScript

Source: Internet
Author: User
Tags instance method

About functions

In JavaScript, a function is actually an object that has a characteristic of a reference type, so you can pass the function directly to the variable, which will represent a pointer to the function "object", for example:

function test (message) {
     alert (message);
   }
   var f = test;
   F (' Hello World ');

You can also assign a function to a variable directly:

var f = function (message) {
     alert (message);
F (' Hello World ');

In this case, the function name can be omitted in the function declaration, because the name has no meaning at this time, we can call the function directly through the variable F.

With function types, we can better understand functions as objects:

var f = new Function ("message", "alert (message);");
F (' Hello World ');

About this

This can be viewed as the actual scope context of the calling function. Compare the execution results of the following functions:

function test () {
     this.property = ' Hello World ';

   }
   Test ();
   alert (window.property);  Because it is called globally, this in the test function actually points to global Object (window)

   var obj = {};
   Test.call (obj);   Specifies the execution context scope by the first parameter of call, so this in the test function points to the obj instance.
   alert (obj.property);   

   var obj2 = {};
   Obj2.test2 = test;   The Obj2 instance method test points to the global test method
   obj2.test2 ();      Because the test method is raised in Obj2, this in the test function also points to obj2 instance
   alert (obj2.property);

Defining types

You can define constructors in JavaScript, constructors are not any different from normal functions, and when you create an instance, if we use the New keyword, then the function has a constructor feature, otherwise it's a generic function, and as shown below, we define a person type:

function person () {
   this.name = ' Xfrog ';
   This. Say = function () {
     alert (this.name);}
   ;
}

When you use the New keyword, you can create a new instance of the person object:

var p1 = new Person ();
P1. Say ();

If you do not use the new keyword, the person function is executed directly, and the Name property and the say method are added to the Window object because the execution context is global in scope:

Person ();
Say ();
Window. Say ();

Prototype

Notice how the person is defined above, when you use new to create a person instance, the person constructor is executed, that is, the Name property and the say method are declared, which can create an efficiency problem, and note the following code:

var p1 = new Person ();
var p2 = new Person ();
var test = P1. Say = = P2. Say;

Comparing the P1 and P2 two say function pointers, returning false, which means that the say method in each person instance is independent, and the fact that the function of the say function is exactly the same, there is absolutely no need to reassign the Say function "Object" for each object, if there is a lot of person instances, will result in a large amount of memory consumption.

If you extract the say function into the global execution scope, you may be able to resolve the secondary problem:

function person () {
     this.name = ' Xfrog ';
     This. Say = Say;   
   }

   function say () {
     alert (this.name);   
   }

   var p1 = new Person ();
   var p2 = new Person ();
   Alert (P1. Say = = P2. Say);
   P1.name = ' Wang ';
   P1. Say ();

Because this is always relevant to the execution context, the Name property of the corresponding instance is returned correctly in the Say method in the P1 and P2 instances. However, the use of this approach is contrary to object-oriented thinking, but also lost the principle of type sealing. A large number of global functions are also created.

To address these shortcomings, JavaScript draws on the concept of a prototype that can be viewed as a shared area of a type, and that the prototype itself is an object, and that the attributes in the object are shared by the type. Each type in JavaScript represents the prototype through the prototype attribute, which allows you to specify a shared method:

function person () {

   }
   Person.prototype.name = ' Xfrog ';
   Person.prototype.Say = function () {
     alert (this.name);
   };

   var p1 = new Person ();
   var p2 = new Person ();
   Alert (P1. Say = = P2. Say);   Returns True

Why this can be done through P1. Say to visit the Say method? This is because the ECMAScript standard sets the lookup order of the type attributes: first on the type's instance, if not, continue to look up on the type prototype, which uses a short-circuit algorithm that finds the first return, considering the following code:

function person () {
     this.name = ' Wang ';
   }

   Person.prototype.name = ' Xfrog ';
   Person.prototype.Say = function () {
     alert (this.name);
   }

   var p1 = new Person ();
   P1. Say ();   will return to Wang

As mentioned above, prototype is actually an object, so can we access it directly? In some browsers implementations (such as Chrome, FIXFOX, etc.) can indeed access the internal prototype objects through the instance's __proto__ properties. This feature indicates that the JavaScript engine holds a reference to prototype within each object by a variable, which ensures that the prototype is shared for an instance of the entire type, for example, You can access the Say method in Chrome browser by using the following methods:

p1.__proto__["Say"] ();

Since the prototype is an object, we can assign an object directly to prototype:

function person () {

   }

   person.prototype = {name: ' Xfrog ', say:function () {
     alert (this.name);
   }};

Note that in this way, it is actually completely replacing the person's prototype, This is slightly different from the way it is Person.prototype.name, because any type, the JavaScript engine adds the default prototype, and in this prototype contains a reference to the constructor, the prototype object attribute constructor, so Usually when using alternative prototype methods, we need to manually add the constructor attribute:

Person.prototype = { 
     Constructor:person,
     name: ' Xfrog ',
     say:function () {
        alert (this.name);
     }
   }

Note that because prototype is shared for the entire type, there may be a problem with the reference type in prototype, the preceding say function as an object and reference type, so the say in each instance points to the same function in the prototype object, which is not a problem in itself. It's also our intention to use prototypes, but for other reference objects, the result may not be what we want:

function person () {
   }

   person.prototype = {
     name: ' Xfrog ',
     obj: {age:18},
     say:function () {
        ale RT (This.obj.age);
     }
   ;

   var p1 = new Person ();
   var p2 = new Person ();
   P1.obj.age =;
   P1. Say ();
   P2. Say ();

P2. Say returns 20 because the Obj property is shared as a prototype property and only one instance exists in memory, so after P1 modification, p2 can only get the modified state. If you want to avoid this situation, you can place the Obj property in the instance:

function person () {
     this.obj = {age:18};
   }

The above is a small series for everyone to talk about the functions of JavaScript, this and the prototype of the entire content, I hope that we support cloud-Habitat Community ~

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.