JS Object-oriented, create, inherit

Source: Internet
Author: User

Very happy, recently harvested a lot of knowledge, and found a lot of things, previously understood are wrong, or is superficial, still think oneself really get to the essence, also very sorry will affect some people go on the wrong road, but this also told us, read any article can not blindly to believe, to practice verification re-verification. Today to re-organize, my understanding of the object-oriented, of course, is not guaranteed to be completely correct, but definitely in progress, and hope to bring some new sentiment.

objects, in layman's terms, are properties and methods. The definition is no longer said, the following is the creation of the object:

1 Creating an object-oriented

var New // Create an empty object obj.name = ' haha 'function() {    alert (obj.name);} Obj.showname ();

Cons: When we want to create multiple object-oriented, repeat the code too much, need encapsulation, so the following method

2 Factory mode

functionCreateperson (name) {//Raw Materials   varobj =NewObject (); //processingObj.name =name; Obj.showname=function() {alert ( This. Name); }   //Factory   returnobj;}varP1 = Createperson (' haha '));p 1.showName ();varP2 = Createperson (' hehe '));p 2.showName ();

This is actually a simple encapsulation function, the whole process like a factory assembly line, so called Factory way

Disadvantage: The type of object created is not recognized. Because all are object, there is no degree of distinction, unlike date, array, and so on, there is a constructor pattern.

3 constructor Mode

We're going to change that in two ways: 1 the first capital of a function name, 2 New keyword call

function Createperson (name) {      this. Name = name;         This function () {         alert (this. Name);       var p1 =new createperson (' haha ');  P1.showname (); var New Createperson (' hehe '); P2.showname ();

1 First letter capitalization, is to distinguish from ordinary functions, the constructor itself is a normal function, but we specifically use it to implement the function of construction, so a special name is called a constructor, any function can become a constructor, depending on how you call the function. Whether new is used.

2 The New keyword was used when calling the function, so what did new do? What's the difference between using no new? Take another look at the following example

function Createperson (name) {     this. Name = name;      This function () {     alert (this. Name);   };  Console.log (Thisnew//createperson{}Createperson (' Haha ');  // window

We'll find that when you call a function with new, the point of this is different. In fact, new mainly did the following things, but the following is only about the behavior, not the internal source code.

functionCreateperson (name) {var res = {};  //declaring an empty object res res._proto_= Createperson.prototype;//The prototype chain of this object points to the prototype of the incoming function, so that res can invoke all the methods under the Createperson prototype  createperson.apply (res);//change this point to Res object   This. name = name;//Res object to add properties, method   This. ShowName =function() {alert ( This. Name);  }; return res;//return This object}

When it comes to new, it's internal, not visible, but it does exist, and the prototype above can probably know the conclusion, the following will say the prototype, and then read it.

Problems with the function construction pattern:

alert (p1.showname==p2.showname);//false

To test this code, the two methods are different, that is, the two objects are not a common method, each new, the system will create a newly created memory, the two objects have their own site, but they have the same function, not shared, certainly not what we want. So there's the next way, prototype mode

4 prototype + construction mode

each function has a prototype property, which is an object, also known as a prototype object, which we can write methods and properties on (though the prototype object has not only properties and methods that we write, but also other, as described below), The instance object created by this function can share the methods and properties under this object . So we just have to put what we want to share in the prototype of the function, and what we don't want to share is created by the constructor.

See a chestnut (prototype + construction)

function Createperson (name) {     this.name = name;} createperson.prototype. showname = function() {     alert (this. name);} var p1 =new createperson (' haha ');p 1.showName (), var p2 = new Createperson (' hehe ');p 2.showName (); Alert ( P1.showname==p2.showname);//true     

The last sentence of the test is true, you can see the constructor under the prototype of the method ShowName () method is all the objects created by this constructor is shared, that is, they share a memory, further said they have a referential relationship, This means that you change the showname of the P1 will also affect P2 showname.

Therefore, when we construct the object, it is generally used in the combination of the prototype pattern and the construction pattern , changing the common prototype pattern with the invariant construction mode, like the chestnut, the constructor of the attribute, because the different object properties are different, the method uses the prototype pattern.

_proto_ Property : Above We just said that the instance object created by the same function can share the methods and properties under the prototype of the function, but how does it work? This is the _proto_ property, each instantiated object has a _proto_ property, which is a pointer to the prototype of the function, which is the address where it was saved. (Thevalue of any object in JS is stored in the heap memory, the variable we declare only holds the actual address of the object, so there is an address to find the object ), so there is always a _proto_ property for each instantiation object, the address of the prototype object that holds the constructor, With this property, you can have all the properties and methods under the prototype object. The _proto_ property is actually a direct connection between instantiating an object and a prototype object.

prototype chain : Each function can be a constructor, each function has a prototype object, each prototype object can also be an instantiated object, for example, you create a function fun, it is the constructor function of the instantiation object, and function of the prototype object and an instance object of object again. So fun has a _proto_ property can access the prototype object of a function, the function prototype object is also an instance object, and there is a _proto_ property that can access the prototype object of object, so through the _proto_ property, A prototype chain is formed. each instantiated object has access to the methods and properties above the chain, so fun is accessible to methods and properties under the object prototype. Virtually all objects can access the prototype object for object.

The access rules of the prototype chain: First look under their own, then go to the primary level of the prototype chain to find. As follows:

function= 3; var New  =10//ten

methods and properties under prototype objects : The prototype object can have three main classes: 1 prototype objects with methods and properties 2 constructor 3 _proto_

constructor: Constructor properties, which are the default properties of each function's prototype object, point to the function. Each instantiated object itself has no constructor property, and each instantiated object has a default of only one _proto_, which is used to connect to the prototype object, which is not directly related to the constructor itself. So its constructor is accessed on the prototype object. So when the constructor of the prototype object changes, the constructor of the instantiated object also changes. But if the object itself is both a prototype object and an instantiated object, it has the constructor property and does not inherit from the prototype object.

Take a look at the following example to verify what we say:

functionCreateperson (name) { This. Name =name;} CreatePerson.prototype.showName=function() {Console.log ( This. name);};varP1 =NewCreateperson (' haha ');p 1.showName (); Console.log (P1.constructor); //Createperson from Createperson.prototype
Console.log (createperson.prototype);//{showname:function () {},constructor:createperson,__proto__:object.prototype}//as can be seen, the prototype object holds 1 of its own added methods, 2 constructors constructor 3 _proto_ (and the connection to the previous layer constructor prototype object)Console.log (Createperson.prototype.__proto__===object.prototype);//true The prototype object itself is an instantiated object of object, and all _proto_ objects that point to ObjectConsole.log (Createperson.prototype.__proto__===object);//false visible is the connection to the prototype object under the constructor, not the constructorConsole.log (CreatePerson.prototype.constructor);//Createperson The default point to the function that created itConsole.log (object.prototype.__proto__);//NULL the end of the prototype chain is nullConsole.log (createperson.__proto__); //Function.prototype Createperson itself is both a constructor and a function instantiation object , with a _proto_ attribute, a prototype object pointing to functionConsole.log (Createperson.constructor);//function inherits from Function.prototype

Console.log (Createperson.prototypeinstanceofCreateperson)//Verify if False on a prototype chain

The literal method defines the prototype :

In order to create the code of the object is more convenient, you must have seen this code, is the literal method:

function= {    showname:function() {alert (varNew Aaa (); Console.log (aaa.prototype); // {showname:function () {},_proto_}    Console.log (Aaa.prototype.constructor); // Object  because it has no constructor attribute, go to the superior prototype object to find, found theobject Console.log (A1.constructor); //o Bject also changed, verifying that it was accessed on the prototype object
So we need to fix the point of the prototype when we write it:
function Aaa () {}aaa.prototype = {  constructor:aaa,  
A1.constructor//AAA

Understanding these, the inheritance is very good understanding, next continue to add. There are errors, welcome to correct.

JS Object-oriented, create, inherit

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.