JS how to do object-oriented

JS itself is not an object-oriented, it is an example of how to do the classes, and classes it? .

1: prototype function object

   Each object has a prototype member functions, pointing to a table,

function a () {}; a.prototype points to a table object

2: __proto__ table

  Each table js (Object) objects, there will be a member of the __proto__, pointing to a table (Object) object. When we visit key Object of this, first in its own table to find, if not found, then look at its __proto__ table, if the table is not __proto__, front and back _ to __proto__ _proto__ table to find, ... only to all the search is completed.;

3: new + function mechanism

  var a = new A (); This is a typical new + mode function,

In which we will JS A function called a constructor function, then the new A () in the end do what things?

(1) had a new reference table object {}, hereinafter referred instance;

(2) the instance, as this, is passed to the function A;

(3) Copy the prototype species in Table A function key, value to below __proto__ instance table inside;

(4) returns a new instance object table instace;

4: js how object-oriented

(1) define a constructor:

Function Person() { … …}

(2) To a prototype table constructor which add member function

   Persion.prototype.set_age = function(age) {}

(3) new + new object obtained after the constructor;

  Var a = new Person (); a is a table {..., __proto__: {set_age: function object (derived from the prototype)}},

 

(4) a.set_age (10); in the example of a table look inside, set_age not found,

__Proto__ inside it to find, locate, so a.set_age () is called to function set_age above, according to the this implicitly passed, after entering set_age this example is a;

 

So, a is an instance of Person, by way of example, the method can be called to class, this is js object-oriented nature, you get to know it? Or dizzy,

If dizzy, look at a few times.

Guess you like

Origin www.cnblogs.com/blakehuangdong/p/11329690.html