Javascript inheritance (2)

Source: Internet
Author: User

This chapter focuses on several important attributes (this, constructor, prototype) in Javascript. These attributes play a vital role in understanding how to implement classes and inheritance in JavaScript.

This

This indicates the current object. If this is used globally, it indicates the current page Object window. If this is used in the function, this indicates what is called Based on the object on which the function is called at runtime. We can also use the apply and call global methods to change the specific point of this in the function.

First, let's look at an example of using this in the global scope:

 
<SCRIPT type = "text/JavaScript"> console. log (this = Window); // true console. log (window. alert = This. alert); // true console. log (this. parseint ("021", 10); // 10 </SCRIPT>

 

This in a function is determined at runtime, rather than at function definition, as follows:

// Define a global function Foo () {console. log (this. fruit);} // defines a global variable, which is equivalent to window. fruit = "apple"; var fruit = "apple"; // In this case, the function Foo points to the window object. // This call method and window. foo (); is a fully equivalent Foo (); // "apple" // custom object, and direct the property Foo of this object to the global function Foo var pack = {fruit: "orange", foo: Foo}; // in this case, this in function Foo points to window. pack object pack. foo (); // "orange"

 

The global functions apply and call can be used to change the point of this in the function, as follows:

 
// Define a global function Foo () {console. log (this. fruit);} // defines a global variable VAR fruit = "apple"; // customizes an object var pack = {fruit: "orange"}; // equivalent to window. foo (); Foo. apply (window); // "apple" // This in Foo = pack Foo. apply (pack); // "orange"

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

 

Because functions in JavaScript are also objects, we can see the following interesting example:

 
// Define a global function Foo () {If (this = Window) {console. log ("this is window. ") ;}} // The function foo is also an object, so you can define the boo attribute 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 (); // This is window. // you can see that this in the function points to the object foo that calls the function. boo (); // This is foo. // use apply to change the point of this in the function to foo. boo. apply (window); // This is window.

 

Prototype

We have used Prototype Simulation class and inheritance implementation in Chapter 1. Prototype is essentially a JavaScript Object. Each function has a default prototype attribute. If this function is used to create a custom object, we call it a constructor. For example, the following simple scenario:

 
// Constructor function person (name) {This. name = Name;} // defines the prototype of person. attributes in the prototype can be referenced by custom objects. 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, such as string, number, array, object, and date. We have reason to believe that these types are implemented as constructors in Javascript, such:

 
// Define the constructor of the array, which is a predefined Function Array () {//...} of JavaScript (){//...} // initialize the array instance var arr1 = new array (1, 56, 34, 12); // However, we prefer the following syntax definition: var arr2 = [1, 56, 34, 12];

At the same time, many methods for Array Operations (such as Concat, join, and push) should also be defined in the prototype attribute. In fact, all the inherent Data Types in Javascript have the read-only prototype attribute (this is understandable: If you modify the prototype attribute of these types, but we can add our own extension method to it.

 
// Extend a method to the array of the inherent JavaScript type to obtain the minimum value. 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 ;}; // call the min method console on any array instance. log ([1, 56, 34, 12]. min (); // 1

Note: There is a trap. After adding an extension method to the array prototype, this extension method will also be recycled when the for-in loop array is used. The followingCodeNote This (assuming that the min method has been extended to the array prototype ):

VaR arr = [1, 56, 34, 12]; var Total = 0; For (var I in ARR) {total + = parseint (ARR [I], 10 );} console. log (total); // Nan

The solution is also simple:

 
VaR arr = [1, 56, 34, 12]; var Total = 0; For (var I in ARR) {If (ARR. hasownproperty (I) {total + = parseint (ARR [I], 10) ;}} console. logs (total); // 103

 

Constructor

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

// Equivalent to VaR Foo = new array (1, 56, 34, 12); var arr = [1, 56, 34, 12]; console. log (ARR. constructor = array); // true // equivalent to VaR Foo = new function (); var Foo = function () {}; console. log (FOO. constructor = function); // true // The constructor instantiates an OBJ object var OBJ = new Foo (); console. log (obj. constructor = Foo); // true // combine the above two sections of code to obtain the following conclusion console. log (obj. constructor. constructor === function); // true

 

But when constructor encounters prototype, interesting things happen. We know that each function has a default prototype attribute, and the constructor of this prototype points to this function by default. For 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 // merge the above two lines of code to obtain the following result console. log (P. constructor. prototype. constructor = person); // true

At that time, when we re-define the prototype of the function (note: the difference from the previous example is that it is not modified but overwritten), the behavior of the constructor is a bit strange, 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); // false console. log (person. prototype. constructor = person); // false console. log (P. constructor. prototype. constructor === person); // false

Why? It turns out that when people. prototype is overwritten, it is equivalent to performing the following code operations:

 
Person. Prototype = new object ({getname: function () {return this. Name ;}});

Constructor always points to the creation of its own constructor, so at this time person. Prototype. constructor = object, that 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 can we fix this problem? The method is also very simple. Just overwrite person. Prototype. constructor again:

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

 

In the next chapter, we will improve the person-employee class and inheritance implementation mentioned in the first chapter.

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.