JavaScript Object-Oriented programming notes

Source: Internet
Author: User

Object : All things are objects. object is a whole and provides some operations externally. For example, a radio is an object, we do not need to know what its internal structure is, only need to use the external button can use the radio.

Object-oriented: The flag for object-oriented languages is that they all have the concept of a class that can create any number of objects that have methods of the same property. Any object is an instance of something, which simply means that when you use an object, you focus only on the functionality provided by the object, not on its internal details.

Object-oriented features : encapsulation, inheritance, polymorphism.

the object-oriented composition in JS : 1. Method (function): process, dynamic 2. Attribute (variable with owning relationship): state, static

An object is a collection of unordered properties whose properties can include basic values, functions, and objects. Each property will have a name, each mapped to a value
Here are some ways to create an object

1. Factory mode

1 function Createperson (name,sex) {//factory method constructs an object2 3 //1. Raw Materials4 Var obj=new object ();//new a blank5         6 //2. Processing7 Obj.name=name;8 Obj.sex=sex;9 Ten obj.showname=function () { One Console.log (' My name is: ' +this.name ') A         } -  - obj.showsex=function () { the Console.log (' I am: ' +this.sex+ ') -         } -          - //3. Factory + return obj;//This step must not be the next -     } +  A var p1=createperson (' Wood ', ' female ');//Every time a createperson is used, a new object is created, and each object has its own way of wasting resources . at var P2=createperson (' triumphantly ', ' Male '); -  - p1.showname (); - p1.showsex (); - p2.showname (); -P2.showsex ();

To construct an object using the factory method step:
1, raw materials
2. Processing
3. Factory
Factory methods are not commonly used because of disadvantages: 1. There is no new 2. Each object has its own function, resulting in a waste of resources
How to solve the two problems? So, look below.

2. Constructor mode

1 The function person (name,sex) {//constructor constructs an object2 This.name=name;//this: Who the current method belongs to (it will be invalidated if new is present in front of the function)3 This.sex=sex;4 5 this.showname=function () {6 Console.log (' My name is: ' +this.name ');7         }8 9 this.showsex=function () {Ten Console.log (' I am: ' +this.sex+ '); One         } A         -     } -  the var p1=new person (' wood ', ' female '); There is no new blank object inside the person function after adding new - var p2=new person (' triumphantly ', ' Male '); -  - Console.log (p1.showname==p2.showname);//fase +  - p1.showname (); + p1.showsex (); A p2.showname (); atP2.showsex ();

Note: the person is generally referred to as a constructor, and the first letter of the constructor is capitalized, which is the encoding specification.
This: Indicates who the current method belongs to, but is not valid here when this encounters new.
Using the build function mode to solve the problem that the above Factory mode is not new.
Then think about it. What happens during the process of creating a new instance using the new operator call constructor? How is a new instance generated?
This method of calling the constructor undergoes the following four steps:
1. Create a new object
2. Assign the scope of the constructor to the new object (so this will point to the new object)
3. Execute the code in the constructor (add properties for this new object)
4. Returning new objects

1 function Show () {2        alert (this); 3     }4    Show ();//Popup Window object (when a function is called in the global scope, the This object always points to the Window object, and the global function belongs to a method of window)  5     new Show ()//Eject obj (this will point to) a newly created object

This example will see more clearly.
As a normal function call:

1 var name = "Mumu"; 2         function Person (name) {  3            this.name = name; 4             this.show = function () {  5            console.log ("I am" + this.name); 6             }  7        }  8  9person        ("JavaScript"); Ten         Console.log (name);//The result is JavaScript

The global variable name is modified

Called as a constructor function:

1 var name = "Mumu";2 function Person (name) {3 this.name = name;4 this.show = function () {5 Console.log ("I am" + this.name);6             }7         }8 9 var Name = new Person ("HTML");Ten Console.log (name.name); OneConsole.log (name);

This points to the new object name, and the global variable name does not change

So here's the question:

1 console.log (p1.showname==p2.showname);//fase

Different instances of the ShowName () function are not the same, then how to solve this problem? Here is a workaround

1 function Person (name,sex) {//constructor2 This.name=name;//this: Who the current method belongs to (it will be invalidated if new is present in front of the function)3 This.sex=sex;4 5 This.showname=showname;6         7     }8 function ShowName () {9 Console.log (' My name is: ' +this.name+ ' I am: ' +this.sex+ ');Ten         } One  A var p1=new person (' wood ', ' female '); There is no new blank object inside the person function after adding new - var p2=new person (' triumphantly ', ' Male '); -  the Console.log (p1.showname==p2.showname);//ture -  - p1.showname (); -P2.showname ();

Define ShowName as a global method so that each instance shares a global method ShowName (). The problem of inequality is solved, but if there are a number of methods in the constructor, which results in a large number of global variables in the code, so that our custom reference types are not encapsulated, and resources are wasted. So how do we solve this problem? See prototype mode

3. Prototype mode

1 function Person (name,sex) {//prototype mode constructor2 Person.prototype.name=name;3 Person.prototype.sex=sex;4 person.prototype.showname=function () {5 Console.log (' My name is: ' +this.name+ ' I am: ' +this.sex+ ');6         }7     }8 9 var p1=new person (' wood ', ' female ');Ten var p2=new person (' triumphantly ', ' Male '); One  A Console.log (p1.showname==p2.showname);//ture -      - p1.showname (); theP2.showname ();

Prototype (prototype) returns a reference to the object type prototype. This property is a pointer to the object. You can allow all object instances to share the properties and methods that it contains, extend system objects, and conserve system resources, so this solves the problem of resource wastage above.
The problem with the prototype is that when an instance changes the property value, the property values of all instances are changed, the property values cannot be initialized, and when an attribute is added to an object instance, this property masks the property of the same name saved in the prototype object, which is a small example:

1 function Person (name,sex) {//prototype mode constructor2 Person.prototype.name=name;3 Person.prototype.sex=sex;4 person.prototype.showname=function () {5 Console.log (' My name is: ' +this.name+ ' I am: ' +this.sex+ ');6         }7     }8 9 var p1=new person (' wood ', ' female ');Ten var p2=new person (' triumphantly ', ' Male '); One      A P1.name= "Xi Xi"; -  - p1.showname ();//XI Xi from the example theP2.showname ();//triumphantly from prototype

Each of the previous methods have their own pros and cons, so what happens when you combine them?

4. Combining the constructor pattern with the prototype mode

1 //constructor pattern defines instance properties2 function Person (name,sex) {3 This.name=name;4 This.sex=sex;5     }6     7 //Prototype mode common methods and shared properties8 person.prototype.showname=function () {9 Console.log (' My name is: ' +this.name+ ' i am ' +this.sex+ ')Ten         } One  A var p1=new person (' wood ', ' female '); -  -P1.showname ();

This method is most commonly used, combining the advantages of both methods to maximize the savings in memory

5. Dynamic Prototyping Mode

1 function person (name, age) {2 this.name = name;3 this.age = age;4 5 //Method6 if (typeof this.showname! = ' function ') {7 Person.prototype.showname = function () {8 Console.log ("My name is:" + this.name);9             }Ten         } One     } A var person1 = new Person ("Mumu", +); -Person1.showname ();

The dynamic prototyping method can determine the initialization prototype by checking whether the method is valid. This approach is perfect, but you cannot use literal rewriting of the prototype, which will cut off the connection between the existing instance and the new prototype.

6. Parasitic constructor mode

1 function Createperson (name, age) {2 var obj=new Object ();3 obj.name = name;4 obj.age = age;5 obj.showname = function () {6 Console.log ("My name is:" + this.name);7         }8 return obj;9     }Ten var person = new Createperson ("Mumu", +); OnePerson.showname ();

This method can be compared with the Factory mode, the creation of the instance method is the same as the constructor, the rest is the same as the Factory mode. Consider this approach if none of the previous methods are applicable, but the object returned by this method constructor is not related to the instance, nor can it depend on the instanceof to determine the object type, so it is recommended or not to be used if you can use other schemas.

7. Secure constructor Mode

1 function person (name, age) {2 var obj = new Object ();3 //define some private variables and functions4 obj.showname = function () {5 Console.log ("My name is:" + name);//defined private variables can only be accessed through ShowName6         }7 return obj;8     }9 var person1 = person ("XI");TenPerson1.showname ();

The so-called secure object refers to the absence of a public attribute. This method is suitable for use in a secure environment because it does not use new to call the constructor, nor does it use this to refer to an instance method. If you want to access its properties, you can only access its internal private properties through the ShowName method.

JavaScript Object-Oriented programming notes

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.