JavaScript Object-Oriented programming

Source: Internet
Author: User
Tags shallow copy

Today, the content of the study is JS object-oriented programming, the following summary of all the content from Ruan Yi Feng Big blog, interested children can poke the original link

Http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html

True, easy to understand, at the same time the first question of the interview (JS inheritance) in my mind gradually three-dimensional up.

JS, an object-oriented programming (OOP) language without class, my first question is how do I generate an instantiated object?

Suppose we have an object cat, which now needs to instantiate a specific "cat", it's easy to write the following code:

1 var cat1 = {}; 2 cat1.name = "Tom"; 3 cat1.color = "BLACK";

This notation of defining objects and assigning properties to objects can be thought of as the most primitive way to generate cat instance objects . Of course we're not stupid enough to be able to write as many instances as we want, so we can go on writing like this:

 1  function   Cat (name, color) { 2  return   { 3   Name:name,  4   col Or:color  5  }  6  }  7  var  cat1 = Cat (" Tom "," Black " 8  var  cat2 = Cat ("Lucy", "white"); 

This is obviously the method of calling the function , but it is not possible to see the contact of two instance objects?? (What do you mean, hello?)

Then let it go naturally to the constructor (add the definition of the constructor: Use this in the normal function, new to the constructor, you can create an instance object)

 1  function   Cat (name, color) { 2  this . Name = name;  3  this . Color =  color;  4  }  5  var  cat1 = new  Cat ("Tom", "BLACK" Span style= "color: #000000");  6  var  cat2 =  New  Cat ("Lucy", "white"); 

To be honest, this is a bit like calling a function above, but the constructor has attribute-holding, which allows you to see the relationship of two instance objects through the "constructor" property and the "instanceof" operator. Although I still do not know why to do so.

The constructor property of each instantiated object is a pointer to the prototype Object!!! Cat1.constructor = = Cat = True

instanceof Empathy//cat1 instanceof Cat = = True

But what about a constant property or method in the constructor? Each time the constructor is instantiated, an identical property or method is produced. Assuming that the program needs to instantiate the prototype object multiple times, which will create the abuse of memory, so the next method to play again!!

prototype Properties

 1  function   Cat (name, color) { 2  this . Name = name;  3  this . Color =     color;  4  }   5  Cat.prototype.kind = "Feline" ;  6  Cat.prototype.eat = function   { 7  alert (' I like to eat Jerry '  8 } 

By introducing the official terminology, each constructor has a prototype property that points to another object, and the instance object inherits the properties and methods on the object, as long as the invariant properties and methods are bound to the object, and they point to the same memory space, which you can test:

1 var New Cat ("Tom", "Black"); 2 var New Cat ("Lucy", "White"); 3 console.log (cat1.eat = = Cat2.cat); True

Instead of purely using constructors, this time the console outputs false, indicating that they actually point to different memory spaces.

Extensions:

Don't feel too used to do it again.

Next is the use of the in operator, presumably most people are familiar with this piece, to determine whether the object contains a property and traverse properties. ( But last time I didn't answer right, hey )

1 inch // true 2 3  for (var in cat1) {4    console.log ("attr-" + key + ":" + Cat1[key]); 5 }

Well, I have a deep understanding of the four ways to generate prototype instances again! According to the computer language routines, completed the encapsulation of nature to discuss how to inherit.

Five ways to inherit constructors

Now that you have a cat object and a new parent object animal, how do I get the cat object to inherit the animal object?

1 function Cat (name, color) {  /// Sub-object 2this     . name = name; 3     this. color = color; 4  5function Animal (species) {  // Parent Object 6     this. Species = "Feline animal"; 7
    • Use the Apply () binding

1 function Cat (name, color) {2     Animal.apply (this, arguments); 3     this. Name = name; 4     this. color = color;    5 }

    • Use prototype mode to point the prototype object of a child object to an instance of the parent object
1 New Animal ();   2 // after modifying the cat's prototype object, it also modifies the object's original pointer to cat to animal, which requires manual re-pointing to the restore

But! Instantiation of the object is also to occupy memory is not, so this writing is not advocated, so there are the following improvements to the wording.

Note: All of the following code that modifies the prototype object requires a re-restore point!!!

    • Prototype Mode improvements
1 cat.prototype = animal.prototype; 2 Cat.prototype.constructor = Cat;

Looks pretty good writing, but will produce such a problem: after the first line of code execution, in order to let Cat.prototype point to restore, so we wrote the second line of code, never thought, the second line of code execution, Animal.prototype's point has become cat!!

And any subsequent changes to Cat.prototype will affect the Animal.prototype, which is obviously unreasonable.

But we can combine the second and the third to create the following notation:

    • Using an empty object to do mediation
1 function Extend (child, parent) {2     var function () {}3     f.prototype = parent.prototype; 4     New f (); 5     Child.prototype.constructor = Child ; 6 }

Instantiating an empty object is almost non-memory, thus excluding the drawbacks of both of these formulations.

    • Copy inheritance
1 functionCopyextend (Child, parent) {2     varc =Child.prototype;3     varp =Parent.prototype;4      for(varKeyinchp) {5C[key] =P[key];6     }7C.uber =p;8 }9 Ten functionAnimal () {} OneAnimal.prototype.species = "Cat Animal"; A  - //called -Copyextend (Cat, Animal);

The inheritance of the constructor is finished, followed by the non-constructor inheritance

In fact, the general function of the inheritance principle and the constructor is similar, mainly using the prototype property and property copy method.

Redefine two objects:

var china = {   //  Parent Object    Nation: "Chinese";} var doctor = {  //  Sub-object    career: "Doctor"}

1. The first method: Let's define an object function

function Object (parent) {    function  f () {}    = parent;     return New f ();}
var Doctor = object (country);
Doctor.career = "Doctor"

Object (), we all know that the prototype property of the constructor is pointing to another object (the instance object does not exist), and the second code is the equivalent of forcing the parent object to be the "other object". The instantiated object (new F ()) automatically inherits all the properties and methods of the "other object", and the instance object returned at this time actually already has the properties and methods of the parent object, and the property of the child object is not exactly the inheritance of the parent object? Very ingenious.

2, the second method, is still the copy attribute, here skim the shallow copy method, straight to the most perfect answer--deep copy

1 functionDeepcopy (Child, parent) {2Child = Child | | {};3      for(varKeyinchparent) {4         if(typeof(Parent[key])) = = = ' object ') {//determines whether a property is an object5Child[key] = (Parent[key].constructor = = = = Array)? [] : {};//determines whether the Property object is an array object or a pure object6Deepcopy (Child[key], Parent[key]);//Recursive copy7}Else {8Child[key] =Parent[key];9         }Ten     } One     returnChild ; A}

Unlike a shallow copy, a deeply copied sub-object inherits the properties of the parent object, even if the property inherited from the parent object is modified, without affecting the contents of the original parent object's properties.

Let's test it out:

 1  china.city = ["Beijing", "Shanghai", "Shenzhen"]; //  2  3  //   call deep Copy method  4  var  doc = Deepcopy (doctor, China);  5  doc.city.push ("Hangzhou"   6  7  console.log (doc.city); //  ["Beijing", "Shanghai", "Shenzhen", "Hangzhou"]  8  console.log (china.city); //  ["Beijing", "Shanghai", "Shenzhen"]  

Above, there is a relatively deep understanding of some of the basic JavaScript object-oriented programming knowledge points. Write blog is too tired ~ or stand on the shoulders of giants, after the more to write more summary Ah!!!


JavaScript Object-Oriented programming

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.