[Original] JavaScript essential knowledge series-Object-Oriented Knowledge string

Source: Internet
Author: User
Summary

Recently, I was looking at the JavaScript advanced programming design (the third edition). The object-oriented chapter contains more than 20 pages, and I went back and forth three or five times. Each time I read different results. The first time I went to sleep, I found a lot of problems, and I couldn't understand anything. I went to bed at night and found that it was like this. After a few days, I found that my handwriting was still based on my memory, so next time, next time...

It is very unreliable to identify things by memory alone, with a long blank head. In particular, there are a lot of technical ideas and principles that can only be ignored. Even if you think clearly at the time, you will forget it after a long time. In addition, there are some things on the Internet, which can only be said to provide a convenient way to view them. After all, most of them are personal summaries, and some concepts are hard to be clearly explained, in addition, when two people talk about the same thing, generally the steps and chapters are different. This makes it easy to form cross-memory, and the more cross-memory, the more chaotic. It's better to look at things with a skeptical attitude. Let's give it a try and find out what it looks like. High-quality and assured books or official stuff are good sources.

You can see it clearly, and your head is clear. record it and make a memo. Conceptual things are written in books, reducing future misleading. The example is hand-written and verified, and a picture is drawn for later understanding.

I. Encapsulation

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

Creation object:Each Object is created based on a reference type. The reference type can be native (Object, Array, Date, RegExp, Function, Boolean, Number, String ), it can also be a custom type.

1 , Constructor Mode
Function Person (name, age) {this. name = name; this. age = age; this. sayName = function () {alert (this. name) ;}} you can use the new operator to create an object instance through the above constructor. Var zhangsan = new Person ('hangsan', 20); var lisi = new Person ('lisi', 20); zhangsan. sayName (); // zhangsanlisi. sayName (); // lisi

PassNewObject creation experience4Steps

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

2. Assign the scope of the constructor to the new object (so this points to this new object); [Person. apply (o)] [the original this of Person points to window]

3. Execute the code in the constructor (add attributes for the new object );

4. Return the new object.

Steps to restore new by code:

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); return o;} test the new instance creation method var wangwu = createPerson (Person, 'wangw', 20); wangwu. sayName (); // wangwu
2 , Prototype mode

Prototype Object Concept: Whenever a new function is created, a prototype attribute is created for the function according to a set of specific rules. This attribute points to the prototype object of the function. By default, all prototype objects automatically obtain a constructor attribute, which contains a pointer to the function of the prototype attribute. With this constructor, you can continue to add other attributes and methods for the prototype object. After a custom constructor is created, its prototype Object only obtains the constructor attribute by default. Other methods are inherited from the Object. After a constructor is called to create a new instance, the instance contains a pointer (internal attribute) pointing to the constructor's prototype object. The pointer to ECMA-262 version 5th is called [Prototype]. There is no standard way to access [[Prototype] in the script, but Firefox, Safari, and Chrome support an attribute _ proto __on each object. In other implementations, this attribute is completely invisible to the script. However, it should be clear that this connection exists between the sample and the prototype object of the constructor, rather than between the instance and the constructor.

This section provides an overview of the relationships between constructors, prototypes, and examples.

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();    //chineselisi.sayCountry();        //chinese alert(zhangsan.sayCountry == lisi.sayCountry); //true

Note:The prototype object of the constructor is used to allow multiple object instances to share its attributes and methods. But this is also prone to problems. If the prototype object contains a reference type, the reference type should be stored as a pointer, so the value will be shared. As follows:

Person. prototype. friends = ['wangwu']; // Add an array type zhangsan to Person. friends. push ('zhaoliu'); // modifications made by Michael Jacob will affect Alibaba (zhangsan. friends); // wangwu, zhaoliualert (lisi. friends); // wangwu, zhaoliu, and Li Si
3 Use the constructor mode and prototype mode in combination.

This mode is the most widely used and the most consistent way to create a custom type. The constructor mode is used to define instance attributes, while the prototype mode is used to define methods and shared attributes. In this way, each instance has its own copy of the Instance attributes, and there is a shared reference to the method, saving the maximum memory.

The prototype is transformed 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,zhaoliualert(lisi.friends); //wangwu
Ii. Inheritance Inherit Basic Concepts

ECMAScript mainly relies on the prototype chain for inheritance (or copy attributes for inheritance ).

The basic idea of prototype chain is to use prototype to inherit the attributes and methods of another reference type. Constructor, prototype, and example: Each constructor has a prototype object that contains a pointer to the constructor, the instance contains an internal pointer pointing to the prototype. Therefore, by making the prototype object equal to another type of instance, the prototype object will contain a pointer to another prototype, correspondingly, another prototype also contains this pointer to another constructor. If another prototype is another type of instance, the above relationship is still established, so that the progressive layers constitute the chain between the instance and the prototype. This is the basic concept of prototype chain.

Reading is not easy to understand. Verify the instance directly.

1 Prototype chain inheritance
Function Parent () {this. pname = 'parent';} parent. prototype. getParentName = function () {return this. pname;} function Child () {this. cname = 'child ';} // the prototype of the sub-constructor is set as the parent constructor instance to form a prototype chain, so that child has the getParentName method Child. prototype = new Parent (); Child. prototype. getChildName = function () {return this. cname;} var c = new Child (); alert (c. getParentName (); // parent

Illustration:

The problem of prototype chain. If the parent class contains the reference type. prototype = new Parent () will bring the reference type in the Parent class to the prototype of the subclass, and the prototype property of the reference type value will be shared by all instances. The problem is returned to [1, 2.

2 , Combination inheritance - Most common inherited party

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.