How JS inheritance?

JS inheritance is based on a code reuse mechanism JS based on the class. In other words, with the code, we do not need to copy the method written before, just by simple way to reuse previously written or co-workers to write their own code. For example, a pop-up layer, we need to make some changes in it. Written a colleague, we inherited it, it's a way to do some changes, or create a new method, and then you can come out with new.

It can use all the features of an existing class, and without having to rewrite these functions extend the case of the original class.
Create a new class by inheriting called "sub-class" or "derived class."
Inherited classes are called "base class", "parent" or "superclass."
After inheriting a clear role, let's explore some of JS implementation inheritance:
// mixed type inheritance (copy) // obj2 obj1 in succession to the member, and can be directly copied to the members obj1 obj2 to the var obj1 = {name: "zs ", age: 10}; var obj2 = {}; // copy obj1 obj2 the members in the for (var Key in obj1) {
obj2 [Key] = obj1 [ Key];
} the console.log (obj1); the console.log (obj2);
obj2 resulting in members and member obj1 is exactly the same, of course, clear that we need, in this case are two obj1 and obj2 different objects.
Mixed type of inheritance appears to be very simple, but there is a problem shared data security.
var obj1 = {name: "zs ", age: 10, car: {name: "mini"}}; var obj2 = {}; // copy obj1 obj2 the members into the for (var key in obj1) {
obj2 [Key] = obj1 [Key];
} // modify the properties car object obj1
obj1.car.name = "Bus";
the console.log (obj1); the console.log (obj2);

Prototyping style inheritance
Recall that when we, first looks in the current object when accessing a member of the object, if not found, then up, then click Find Now in the prototype chain, if the whole prototype chain the member does not exist, it returns undefined.
So, we want to have access to the B object in the object A, B in addition to adding members to the A, such as: mixed type, we can also consider adding members to B of A prototype chain to achieve shared object members.
Animal function () {
}
Animal.prototype.name = "Animal"; function Person () {
} // modify the Person prototype object
Person.prototype = Animal.prototype;

Person.prototype.useTool = function () {
console.log("use fire");
}var p = new Person();console.log(p);var ani = new Animal();console.log(ani);
画图分析:

  1. Initially, the two objects Animal and Person does not have any relationship, so each member can only access their own
    Here Insert Picture Description
  2. Now, if you want to inherit Animal Person objects objects, just to Person prototype object is modified to the Animal prototype object can be
    Here Insert Picture Description
    achieved in this way is called inheritance prototype inheritance, is relatively easy to achieve, and then mixed in the same style, there is data sharing.
    Implementation of the prototype chain inheritance
    prototypal inheritance
    in previous lessons, we talk about the type of prototype inheritance, this inheritance is to modify the subclass object prototype pointing to the parent class prototype object, as in the previous MyArray Array prototype object is the execution of the .
    In this way there is a problem that can only inherit a member of the parent object prototype, but can not inherit a member of the parent object.
    Animal function () {
    this.color = "Red";
    }
    Animal.prototype.weight = 100; the Person function () {
    }
    Person.prototype = Animal.prototype; new new var P = the Person (); the console.log (P) ;
    Person.prototype = Animal.prototype; prototypal inheritance
    at this time to create out of the Person object p can access the properties Animal weight in, but can not access the color attribute. Figure understand
    Here Insert Picture Description
    it, if we both inherited members prototype object, but also inherited members in the instance of an object, you should use the prototype chain to inherit this section of the
    function Animal () {
    this.color = "Red";
    }
    Animal.prototype.weight = 100; function Person () {
    }
    Person.prototype = new Animal();var p = new Person();console.log(p.color);//red

Here Insert Picture Description
Use inheritance to inherit the prototype chain to more members. But the question remains:

  1. Share issue
  2. Unable to pass arguments to the constructor
    complex inheritance example prototype chain ---
    Object-Animal-Boy the Person-
    basic Object.create method using
    a create method on constructor Object exists, the role of this method is used to create objects .
    This method can take about two kinds of parameters
  3. null

  4. Create an empty object, this empty object in even the most basic prototype object are not

  5. Objects

  6. Create an object passed in, and set the object's prototype object to the current parameters

  7. Here Insert Picture Description
    Utilization of this method is relatively low, asking everyone to know there is such a way of creating an object can be.
    The basic call method using the methods and apply
    call and apply methods action:

  8. 方法借用2. 设置方法中this的指向
    var obj1 = {
    name:"Neld",
    age:10,
    showInfo:function () {
    console.log("name:"+this.name,"age:"+this.age);
    }
    }var obj2 = {
    name:"Lily",
    age:12
    }
    obj1.showInfo();//name:Neld age:10
    obj2.showInfo();//obj2.showInfo is not a function
    obj1对象中有showInfo方法,而obj2对象中没有,所以如果直接使用obj2调用showInfo方法的时候抛出错误信息。
    如果我们临时需要使用obj2调用showInfo方法来打印出name和age属性的值,此时可以使用这里的call或者apply方法来实现。
    obj1.showInfo.call(obj2);//name:Lily age:12
    obj1.showInfo.apply(obj2);//name:Lily age:12
    这就是把obj1中的showInfo方法借用给obj2使用。
    同时我们观察到,在showInfo方法中使用到了this关键字,在obj2借用该方法的时候,其中的this已经指向了obj2对象,这就要达到修改方法中this关键字的指向的目的。
    call和apply方法的作用是完全一样的,那么他们的区别是什么呢?继续往下分析。
    var obj1 = {
    name:"Neld",
    age:10,
    add : function (a, b) {
    return a + b;
    }
    }var obj2 = {
    name:"Lily",
    age:12
    }console.log(obj1.add.call(obj2, 1, 2));//3//console.log(obj1.add.apply(obj2, 1, 2));//CreateListFromArrayLike called on non-objectconsole.log(obj1.add.apply(obj2, [2, 2]));//4
    在obj1中定义一个带有两个参数的方法,obj2中没有,问题一样,obj2也要使用到obj1中的add方法,此时使用call或者apply借用即可。
    此时新的问题是,在调用add方法的时候参数应该如何传递?
    call方法:
    ​ 将this指向的对象作为第一个参数,其他参数依次传递即可
    apply方法:
    ​ 将this指向的对象作为第一个参数,其他参数封装到数组中传递
    ​ 如果没有使用数组,程序报错。
    以上就是call和apply的基本使用,这两个方法在后续的课程中会大量的使用到,所以必须引起重视。
    借用构造函数继承说明
    所谓借用构造函数,就是在子构造函数中调用父构造函数,达到继承并向父构造函数传参的目的。
    function SuperClass(name,age) {
    this.name = name;
    this.age = age;
    }
    SuperClass.prototype.fun1 = function () {
    console.log("name:",this.name,"age:",this.age);
    }function SubClass(color) {
    this.color = color;
    }
    SubClass.prototype = new SuperClass("xxx",10);//继承父构造函数并设置name和age的值
    SubClass.prototype.fun2 = function () {
    console.log("color:",this.color);
    }var sub = new SubClass("red", "Neld", 10);var sub2 = new SubClass("red", "Lily", 12);console.log(sub);console.log(sub2);
    上面是原型链的继承,这种方式存在一个问题是,在创建不同对象的时候,无法为其继承过来的成员赋值。
    这里的sub和sub2两个对象的name和age属性值都是“xxx”和10,很明显是不满足我们需求的。
    那么我们来看看借用构造函数是否能解决这个问题呢?
    function SuperClass(name,age) {
    this.name = name;
    this.age = age;
    }
    SuperClass.prototype.fun1 = function () {
    console.log("name:",this.name,"age:",this.age);
    }function SubClass(color, name, age) {
    this.newMethod = SuperClass;//①
    this.newMethod(name, age);//②
    this.color = color;
    delete this.newMethod;//③
    }//SubClass.prototype = new SuperClass();
    SubClass.prototype.fun2 = function () {
    console.log("color:",this.color);
    }var sub = new SubClass("red", "Neld", 10);var sub2 = new SubClass("red", "Lily", 12);console.log(sub);console.log(sub2);
    ①、②、③处代码是实现借用构造函数的关键。下面一一作出解释:
    ①:将父对象的构造函数设置为子对象的成员
    ②:调用这个方法,想过类似于将父构造函数的代码放在子构造函数中来执行
    function SubClass(color, name, age) {
    this.newMethod = SuperClass;
    this.name = name;//父构造函数中的代码
    this.age = age;//父构造函数中的代码
    this.color = color;
    delete this.newMethod;
    }
    这样看应该更直观一点,执行之后就是在为当前创建出来的对象封装name和age属性。
    ③:在子构造函数中,newMethod仅仅为了在②调用父构造函数使用,用完之后也就没了价值,所以,直接删除该方法即可
    Here Insert Picture Description
    可以看到,借用构造函数继承方式解决了原型链及继承的问题。
    下面再看看另外一种借用构造函数的实现方式(使用call或apply):
    function SubClass(color, name, age) {
    //SuperClass.call(this,name,age);
    SuperClass.apply(this,[name,age]);
    this.color = color;
    }
    我们可以使用call或apply更简单快捷的实现和上面一样的效果。
    以上就是借用构造函数继承(也要对象冒充)的两种实现方式。当然,这种继承方式都存在下面两个问题:
  9. 如果父子构造函数存在相同的成员,那么子构造函数会覆盖父构造函数中的成员
  10. Members can not inherit the prototype chain
    combination of the basic structure of inheritance
    based on the prototype chain of inheritance and succession borrow constructors exist in two ways, we propose a solution --- a combination of inheritance, is to use the two together.
    SubClass function (Color, name, Age) {
    //SuperClass.call(this,name,age);
    SuperClass.apply (the this, [name, Age]); // constructor inherited members
    this.color = color;
    }

SubClass.prototype = new SuperClass (); // inherited members on the prototype chain
summary: ECMAScript implementation inheritance more than one way. This is because the inheritance mechanism of JavaScript is not clearly defined, but by imitating achieved. This means that all the details are not fully processed inherited by an interpreter. As a developer, you have the right to decide the most appropriate way of inheritance.
Draw a complete prototype chain structure diagram
This section focuses on the function object's prototype chain structure. The complete structure is as follows:
Here Insert Picture Description
Inheritance summed up an inherited constructor (call, apply) different instance attribute inheritance in the same manner by the prototype parent object point prototype sub-object, but it must be noted, can not sub. prototype = inherit the parent object's prototype Super.prototype. Because of this, the equivalent of parent and child objects simultaneously share a single prototype, child objects to make changes, it will affect the image of the father, this time the prototype chain of the parent object has been destroyed, so for this situation must pay attention!

Guess you like

Origin blog.51cto.com/13007966/2459860