Class inheritance and prototype type JavaScript inheritance

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

  Most recently in the "JavaScript pattern" this book, although the content relatively obscure, but fine found book content is strong. Just after the fourth chapter -- the inheritance, to make notes.

  The book describes the three types of inheritance, class inheritance, the inheritance and class inheritance with prototype. Class inheritance and prototype based inheritance by more, the last one is more like a kind of sharing and expanding. This paper mainly discusses the former two. In fact, is to discuss how to make a child object to inherit the properties and methods of the parent object.

  1. Class inheritance
function Parent(name){
    this.name = name;
    this.sex = "male";
}

Parent.prototype.getName = function(){
    alert(this.name);
}

Parent.prototype.show = function(){
    alert("I'm here.");
}

function Child(age){
    this.age = age;
}

Here we see the parent class has name and sex properties, and the getName method and show method, and child only the age attribute. Parent and child are the constructor.

Property let child with parent, we can use apply or call to the constructor binding parent to child, as follows:

function Child(age){
    this.age = age;
    Parent.call(this,"Jim")
}

var c = new Child(12);
console.log(c.name)  //Jim
console.log(c.sex)   //male

But this method inherits the parent constructor, and did not get the methods defined on parent.prototype, so the c.getName () and c.show (c) will be prompted without the method.

Of course, the above mentioned method is not the type of inheritance, then we have a look how to implement class type inheritance with prototype model.

function Child(age){
    this.age = age;
    Parent.call(this,"Jim");
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var c = new Child(12);

Inherited by prototype, can inherit the properties and methods of the superclass of all. Of course, if there is no

Parent.call(this,"Jim")

This sentence, although C has inherited the name property and the getName method of the parent, but the result is undefined Oh, but it is the succession to the.

We regard child.prototype as an instance of parent, which is to rewrite the child prototype object, any prototype object has a constructor attribute, pointing to its constructor. That is to say, the constructor property child.prototype of the object, is a pointer to child. Here we rewrote the prototype object to its original value, so a new prototype object does not have a constructor property, we need to manually add, or behind the inheritance chain ” ” problem.

Another method is to create an empty object as an intermediary to achieve, but this method has a problem, please see

function Child(age){
    this.age = age;
}
function F(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
var c = new Child(12);

Here we create F () is used as a null object intermediary, we test

console.log(c.age)   //undefined
c.show()    // "I'm here."

Here's the problem, this method only inherit the properties and methods of the parent class prototype, not inherited from the parent class constructor, not to mention the attribute has a parent class, such as sex.

But the solution is very simple, as long as we use the previously mentioned call or apply to the constructor parent binding to the child on it, so as long as the child () your constructor

Parent.call(this,"Jim")

In order to simplify, we can combine the method of apply or call and empty object, package them into a extend function

function extend(subClass, superClass) {
  var F = function() {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;
}

As long as we write extend (Child, Parent), and in the Child () constructor constructor can bind Parent. But the trouble is if child doesn't want to inherit from parent, want to inherit from the uncle class, we have to modify the code in the child constructor,

Parent.call(this,"Jim")

Amended as

Uncle.call(this,"Jim")

In order to solve this problem, in the book the extend function on the line improvement

function extend(subClass, superClass) {
  var F = function() {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype;
  if(superClass.prototype.constructor == Object.prototype.constructor) {  //Ensure that the constructor property is set to the correct
    superClass.prototype.constructor = superClass;
  }
}

Then write in the subclass of child

Child.superclass.constructor.call(this, “Jim”);

Of course the hate Jim you can change to name, and through the Child argument constructor afferent. Or directly into apply (this, arguments), as long as you can into the parameters.

OK, class inheritance probably was this meaning. In fact, the name I feel strange, and often these methods mistakenly believe that the prototype type inheritance, after all, you cannot do without prototype. Presumably this method is similar to other object-oriented programming language class.

  2.  The prototype based inheritance

  Then the prototype type inheritance is what? We first summarize the main points of lower class type inheritance: 1 first used the structure of a class declaration to define object, is actually a constructor; 2 the next instantiation to create a new object. Objects created in this way have a copy of all instances of the class attribute, each instance methods exist only one, but every object has a pointer to it. If the class has a lot of examples, each instance has a copy of each attribute, the more memory.

  When using the prototype type inheritance we don't need to create a constructor defined object structure, we create an object, and the properties and methods need to make is inherited by child objects are written on this object, this object is referred to as the prototype object, and then through a clone function let the prototype object is inherited by child objects.

function clone(object) {
    function F() {}
    F.prototype = object;
    return new F;
}

var Parent = {
    name: "Jim",
    sex: "male",
    getName : function(){
        return this.name;
    }
}

var c = clone(Parent);

The book with the name clone I think is appropriate, after all this is not on the prototype object to copy, only the prototype points to the prototype object, thus the prototype chain to obtain the properties and methods of the prototype object. For example, a A object is no rights, but she found a godfather, is also the prototype object. For the godfather is the process of the clone function in the F.prototype = object. So A can rely on, the next time you do not have the ability to do things, you can find her godfather's prototype objects do. Of course, it's not a proper. In a word by a prototype object to a prototype object, so that an object has properties and methods of the prototype object. Because of the attributes and methods does not own, can be through the prototype chain to prototype objects can, of course the object can define its own properties and methods, but also on the properties and methods inherited rewritten, become the properties and methods of their own.

console.log(c.name);    //Jim
c.name = "Tom";
c.getName();   //Tom

You can find prototype inheritance than type inheritance is more concise, but this method has a problem, that is to read and write the unequal. var c = clone(Parent)In fact only creates an empty object {}, but its prototype pointing to the prototype object. So in our first console.log (c.name) when, just through the prototype chain to the name attribute prototype object, and then c.name = "Tom" this word not to rewrite the name property is inherited from the prototype object from the name attribute, it created a new self, we run console.log (c) have a look, get the following information

F {age: 12, name: "Tom", name: "Jim", sex: "male", getName: function}
    name: "Tom"
    __proto__: Object
        getName: function (){}
        name: "Jim"
        sex: "male"            

See the two name attributes, one is the C itself, a prototype object. If c.name is Tom, because they have the property, do not have to go to the prototype object found. Then c.getName () is how much, is Tom Oh, because C has a getName method, and the method of this is the object to call the method, this is C, so is Tom.

All here is a more cheating problem is, when the prototype object that contains an array and object type members, just look at the code.

var Parent = {
    name: "Jim",
    sex: "male",
    hobby: ["sports"],
    children:{son:"Jack",daughter:"Lily"},
    getName : function(){
        return this.name;
    }
}

var c = clone(Parent);
c.hobby.push("game");
c.children.son = "James";

console.log(Parent.hobby);   //["sports","game"]
console.log(Parent.children.son);   //"James"

You see, Parent tampering. It is not difficult to understand, because the newly created C itself does not have hobby and children, only to change the prototype object. So if you want to modify only on C hobby and children, we must first create a copy.

var c = clone(Parent);
c.hobby = [];
c.children = {son:"Jack",daughter:"Lily"};
c.hobby.push("game");
c.children.son = "James";

console.log(Parent.hobby);   //["sports"]
console.log(Parent.children.son); //"Jack"

console.log(c.hobby); //["game"]

console.log(c.children.son); //"James"

But it would have to know the array of structures and members of an object and the original value when successive array and member of the object, and is more trouble. The book also gives a solution, probably thought is through the method of prototype object to create an array or object, such as a method call C prototype object can inherit the array or member object.

  Comparison of 3 kinds of type inheritance and the prototype based inheritance

  The two methods can achieve good inheritance effect. In contrast, type inheritance may be more suitable for object-oriented programming, and prototype based inheritance is the JavaScript language, it is strange, especially mentioned the read and write is not equal, sub class modifications may even affect the parent class and other inherited the superclass subclass. But the prototype based inheritance is more simple, at the same time, memory usage is more economical, because it is shared by the prototype object properties and methods that, unlike type inheritance in each instance has a copy, uses more memory. The two way of succession each have advantages and disadvantages, how to choose depends.

  Well, in the first blog blog Park managed code is finished, the level is limited, if any hope you exchange.

Reference material:

1 to Javascript inheritance mechanism 

The 2.JavaScript design pattern (Ross Harmes  /  Dustin Diaz   the fourth chapter -- inheritance)

  

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Webb at November 15, 2013 - 12:00 PM