JavaScript's object-oriented explanation

Source: Internet
Author: User
Tags function prototype

Every time I talk about JavaScript to object-oriented, I always feel that I understand, but do not know how to say, this is indefinitely to performance, so, every time a said, will go everywhere to find information, bits and pieces to see some, feel to understand, but over time, as if do not know what is going on, so, Looking for information everywhere, but I was missing the object? Do not understand what the object is, so that the reality of looking for objects, JavaScript is also looking for objects! Oh, how embarrassing! Until I saw a sister paper writing "Must-know JavaScript object-oriented", I understand what object-oriented is, this is not to say that I want to find the object is this sister paper??

Object creation: 1 Creating an object-oriented
var New  = ' haha 'function() {   alert (obj.name);} Obj.showname ();

Cons: When we want to create multiple object-oriented, repeat the code too much, need encapsulation, so there is a factory method.

2 Factory mode

functionCreateperson (name) {varobj =NewObject ();//Raw MaterialsObj.name = name;//processingObj.showname =function() {alert ( This. Name); }    returnObj//Factory}varP1 = Createperson (' haha '));p 1.showName ();varP2 = Createperson (' hehe '));p 2.showName ();//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

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

We change in these two ways:
1  function Name uppercase
This is to distinguish from ordinary functions, the constructor itself is actually a normal function, but we specifically use it to implement the function of the structure, so a special name called the constructor, Any function can be a constructor, depending on how you call the function, which is called when new is used. The
2 new keyword call
uses the New keyword when calling a function, so what does 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//CreatepersonCreateperson (' 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) {varobj = {};//declares an empty object, objobj._proto_=Createperson.prototype; //point the _proto_ property of this object to the prototype object of the constructor, so that obj can invoke all the methods under the Createperson prototype object, where the prototype first knows the conclusion, as the following will say. Createperson.apply (obj);//use the Apply method to point this to the Obj object     This. name = name;//obj Object Add property, Method     This. ShowName =function() {alert ( This. Name);     }; returnObj//return This object}

Problems with the function construction pattern:

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

Cons: These two objects are not a common method, each new one, the system will be newly created a 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 + construction mode

4 prototype + construction mode

Prototype: Each function has a prototype property, which is an object, also known as a prototype object, we can write methods and properties on it (but the prototype object is not only the properties and methods we write, there are other, described below), and through this function created by the instance object, Can share the methods and properties under this prototype 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 =function() {    alert (this  . Name);} var p1 =new createperson (' haha ');p 1.showName (); var New Createperson (' hehe ');p 2.showName (); alert (P1.showname==p2.showname); // true

The test is true, the visible ShowName () method is shared, that is, they share a memory, further saying that they have a referential relationship, that is, you change the P1 showname will also affect P2 showname.

_proto_ Properties:
The instance object created by the same function can share the methods and properties under the prototype of this function, but how does it do it? This is the _proto_ attribute.
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. (The value of any object in JS is stored in the heap memory, the variable we declare is just a pointer, the actual address of the object is saved, so there is an address to find the object),
So all in all, each instantiated object has the _proto_ property, the address of the prototype object that holds the constructor, and through which all the properties and methods under the prototype object can be owned, and the _proto_ property is actually the connection between the instantiated object and the prototype object.

Prototype chain:
Each function can be a constructor, each of which has a prototype object, and each prototype object can also be an instantiated object, for example, you create a function fun, which is an instantiated object of the constructor function, and the prototype object of function, which is also an instance object of object. 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

Prototype objects:
There may be three properties under the prototype object:
1 prototype objects with methods and properties 2 constructor 3_proto_ property
Constructor: constructor properties, which are the default properties of each function's prototype object, point to the function.
Each instantiation object itself has no constructor property, and they have only one _proto_ attribute below, 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 Instanced object, it has the constructor property and does not need to be accessed 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.prototypeConsole.log (createperson.prototype);//{Showname:{},constructor:createperson,__proto__:object.prototype}//visible, the prototype object holds the1self-added methods,2Constructor Constructor3_proto_ (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 Createperson.prototype is an object instantiation and a prototype object, so it has constructor propertiesConsole.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_ property, a prototype object pointing to functionConsole.log (createperson.constructor);//function inherits from Function.prototypeConsole.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:

functionAaa () {}aaa.prototype={showname:function() {}, Showsex:function(){}}; varA1 =NewAaa (); Console.log (aaa.prototype);//{showname:function () {},_proto_}//you'll find constructor gone, because it's the equivalent of a re-assignment Aaa.prototypeConsole.log (Aaa.prototype.constructor);//object because it does not have the constructor attribute, go to the ancestor of the prototype object, found an objectConsole.log (a1.constructor);//object is also changed to verify that it is accessed on the prototype object

So we need to fix the point of the prototype when we write it:

function= {constructor:aaa, num1:function() {alert ()}} var New Aaa (); A1.constructor     // Aaa

Understanding of these, the subsequent succession is very good understanding, not to be continued. If there are errors, please correct them.

Reprint Source: http://www.jianshu.com/p/845ad9b78201

Feel Jane Books, nuggets and other such blog-like website to see the comfortable point, I am not going to shift positions! What do you think?

JavaScript's object-oriented explanation

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.