JavaScript Object-oriented knowledge knot (read JavaScript Advanced Programming (Third Edition)) _javascript tips

Source: Internet
Author: User
Tags instance method
The first time to be swallowed, superficial understanding, feeling suddenly, the result of sleep at night to find a lot of problems, what do not understand, see the second time, found that is so. After a few days to use, found that the original handwriting is still in the memory, so the next time, next time ...

Only by remembering to find out things are not reliable, time a long head blank. In particular, a lot of technical ideas and principles, only see not practice, even at that time to think particularly clearly, too long will forget. What's more, some things on the internet can only be said to provide a convenient way to view, afterwards or own summary as good, after all, most of them are personal summary, some concepts difficult to say very clearly, and two people talk about the same thing, generally speaking of the steps and chapters are different, so it is easy to form a cross memory, the more cross memory more confusion. Or a skeptical attitude to see things better, and try to know exactly how it looks, knowledge string. High-quality, guaranteed books, or some official stuff, are good sources.

While I can see it, the head is clear, record, make a memo. The conceptual stuff is on the books, reducing future misleading. Example handwriting verification, and then draw a picture, so that after a look at the understanding.

First, packaging

Object definition: ECMA-262 defines an object as: "A collection of unordered attributes, where properties can include basic values, objects, or functions."

Create object: Each object is created from a reference type that can be a primitive type (object, Array, Date, RegExp, Function, Boolean, Number, String), or a custom type.

1, the constructor function pattern
Copy Code code as follows:

function person (name, age) {
THIS.name = name;
This.age = age;
This.sayname = function () {
alert (this.name);
}
}
Use the new operator with the above constructor to create an object instance.
var Zhangsan = new Person (' Zhangsan ', 20);
var lisi = new Person (' Lisi ', 20);
Zhangsan.sayname ();//zhangsan
Lisi.sayname (); Lisi

Creating an object from new is going through 4 steps

1. Create a new object; [var o = new Object ();]

2. Assign the scope of the constructor to the new object (so this points to the new object); [Person.apply (O)] [person's original this is pointing to window]

3, execute the code in the constructor (add attributes for this new object);

4, return the new object.

To restore new by code:
Copy Code code as follows:

function Createperson (P) {
var o = new Object ();
var args = Array.prototype.slice.call (arguments, 1);
o.__proto__ = P.prototype;
P.prototype.constructor = P;
P.apply (o, args);
}
To test a new creation instance method
var Wangwu = Createperson (person, ' Wangwu ', 20);
Wangwu.sayname ();//wangwu


2. Prototype mode

Prototype Object concept: Whenever you create a new function, you create a prototype attribute for the function based on a specific set of rules, which points to the prototype object of the function. By default, all prototype objects will automatically get a constructor (constructor) property that contains a pointer to the function where the prototype property is located. With this constructor, you can continue to add additional properties and methods to the prototype object. When a custom constructor is created, its prototype object only obtains the constructor property by default, and the other methods inherit from object. When the constructor is called to create a new instance, the internal of the instance will contain a pointer (internal property) that points to the stereotype object of the constructor. ECMA-262 5th Edition Tube This pointer is called [[Prototype]]. There is no standard way to access [[Prototype]] in the script, but Firefox, Safari, and chrome support a property __proto__ on each object, and in other implementations, this property is completely invisible to the script. However, the really important point to be clear is that the connection exists between the sample and the stereotype object of the constructor, not between the instance and the constructor.

This section basically outlines the relationship between constructors, prototypes, and examples, and the following illustration shows a clearer

Copy Code code as follows:

function person (name, age) {
THIS.name = name;
This.age = age;
}
Person.prototype.country = ' Chinese ';
Person.prototype.sayCountry = function () {
alert (this.country);
}

var Zhangsan = new Person (' Zhangsan ', 20);
var lisi = new Person (' Lisi ', 20);

Zhangsan.saycountry (); Chinese
Lisi.saycountry (); Chinese

Alert (Zhangsan.saycountry = = Lisi.saycountry); True

Note Place: The prototype object of the constructor, the primary purpose is to have multiple object instances share the properties and methods it contains. But this is also a problem prone place, if the prototype object contains reference types, then the type should be referenced by the pointer, so it will result in value sharing. As follows:
Copy Code code as follows:

Person.prototype.friends = [' Wangwu ']; Person to add an array type
Zhangsan.friends.push (' Zhaoliu '); John Modification will affect dick
alert (zhangsan.friends); Wangwu,zhaoliu
alert (lisi.friends); Wangwu,zhaoliu Dick a lot more.

3. Combined use of constructor patterns and prototype patterns

This pattern is the most widely used and most agreeable way to create a custom type. The constructor pattern is used to define instance properties, which are used to define methods and shared properties. In this way, each instance has its own copy of the instance attribute, and there is a shared reference to the method, saving the maximum amount of memory.

The prototype model is modified as follows:
Copy Code code as follows:

function person (name, age) {
THIS.name = name;
This.age = age;
This.friends = [' Wangwu '];
}

Person.prototype.country = ' Chinese ';
Person.prototype.sayCountry = function () {
alert (this.country);
}

var Zhangsan = new Person (' Zhangsan ', 20);
var lisi = new Person (' Lisi ', 20);

Zhangsan.friends.push (' Zhaoliu ');
alert (zhangsan.friends); Wangwu,zhaoliu
alert (lisi.friends); Wangwu

Second, the succession

Inheriting basic concepts

ECMAScript relies primarily on prototype chains to implement inheritance (or it can be inherited by copying attributes).

The basic idea of a prototype chain is to make a reference type inherit properties and methods of another reference type using a prototype. The relationship between constructors, prototypes, and samples is that each constructor has a prototype object that contains a pointer to the constructor, and the instance contains an internal pointer to the prototype. So, by having the prototype object equal to an instance of another type, the prototype object will contain a pointer to another prototype, and, correspondingly, a pointer to another constructor is included in the other prototype. If another prototype is another type of instance, then the relationship is still set up, so the level of progression, forming the chain of examples and prototypes. This is the basic concept of the prototype chain.

It's not easy to understand if you read it around. The validation is demonstrated directly through an instance.

1. Prototype chain inheritance
Copy Code code as follows:

function Parent () {
This.pname = ' parent ';
}
Parent.prototype.getParentName = function () {
return this.pname;
}

function Child () {
This.cname = ' child ';
}
The child constructor prototype is set as an instance of the parent constructor, forming a prototype chain, allowing the children to own the Getparentname method
Child.prototype = new Parent ();
Child.prototype.getChildName = function () {
return this.cname;
}

var C = new Child ();
Alert (C.getparentname ()); Parent

Graphic:


The problem with the prototype chain is that if a reference type is included in the parent class, the reference type in the parent class is brought to the prototype of the subclass by Child.prototype = new parent (), and the prototype property of the reference type value is shared by all instances. The question is back to [A, 2] section.

2, combined inheritance-the most common way to inherit

Combined inheritance (combination inheritance) is a combination of prototype chains and borrowed constructors (apply, call) techniques. The idea is to implement the inheritance of prototype properties and methods using the prototype chain, and to inherit the instance property by borrowing the constructor. In this way, the method can be defined on the prototype to realize the reuse of functions and to ensure that each instance has its own attributes.
Copy Code code as follows:

function Parent (name) {
THIS.name = name;
this.colors = [' Red ', ' yellow '];
}
Parent.prototype.sayName = function () {
alert (this.name);
}

function child (name, age) {
Parent.call (this, name); Second call to Parent ()
This.age = age;
}

Child.prototype = new Parent (); The first call to parent (), the properties of the parent class
Child.prototype.sayAge = function () {
alert (this.age);
}

var C1 = new Child (' Zhangsan ', 20);
var C2 = new Child (' Lisi ', 21);
C1.colors.push (' Blue ');
alert (c1.colors); Red,yellow,blue
C1.sayname (); Zhangsan
C1.sayage (); 20

alert (c2.colors); Red,yellow
C2.sayname (); Lisi
C2.sayage (); 21st

The problem with combinatorial inheritance is that you call a two-time superclass constructor at a time: the first time you create a subtype prototype, and the other one is inside the subtype constructor. This results in an override of the property, which contains the properties of the parent class, and the subclass's prototype object also contains the properties of the parent class.

3, parasitic combination inheritance-the most perfect way to inherit

The so-called parasitic combination inheritance, that is, by borrowing the constructor to inherit the property, through the prototype chain of the hybrid form to inherit the method. The basic idea behind it is that you don't have to call a superclass constructor to specify the stereotype of a subclass, all we need is a copy of the Super type prototype.
Copy Code code as follows:

function extend (child, parent) {
var F = function () {}; To define an empty constructor
F.prototype = Parent.prototype; Set as a prototype of the parent class
Child.prototype = new F (); The prototype of the subclass is set to an instance of F to form a prototype chain
Child.prototype.constructor = child; Re-specifying the subclass constructor pointer
}

function Parent (name) {
THIS.name = name;
this.colors = [' Red ', ' yellow '];
}
Parent.prototype.sayName = function () {
alert (this.name);
}

function child (name, age) {
Parent.call (this, name);
This.age = age;
}

Extend (child, Parent); Implementing inheritance
Child.prototype.sayAge = function () {
alert (this.age);
}

var C1 = new Child (' Zhangsan ', 20);
var C2 = new Child (' Lisi ', 21);

C1.colors.push (' Blue ');
alert (c1.colors); Red,yellow,blue
C1.sayname (); Zhangsan
C1.sayage (); 20
alert (c2.colors); Red,yellow
C2.sayname (); Lisi
C2.sayage (); 21st
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.