Home  >  Article  >  Web Front-end  >  Summary of the six major patterns of javascript inheritance_javascript skills

Summary of the six major patterns of javascript inheritance_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:04:361049browse

1. Prototype chain

function SuperType(){
this.property = true;
}

SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function (){
return this.subproperty;
};
var instance = new SubType();
alert(instance.getSuperValue()); //true

The essence of the implementation is to override the prototype object and replace it with an instance of the new type.

2. Borrow constructor

function SuperType(){
this.colors = ["red", "blue", "green"];
}
function SubType(){
//继承了SuperType
SuperType.call(this);
}
var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
var instance2 = new SubType();
alert(instance2.colors); //"red,blue,green"

If you just borrow the constructor, you will not be able to avoid the problems of the constructor pattern - the methods are all defined in the constructor, so function reuse is out of the question. Moreover, methods defined in the supertype's prototype are not visible to subtypes, so all types can only use the constructor pattern. Considering these problems, the technique of borrowing constructors is rarely used alone.

3. Combination inheritance

function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);

};
function SubType(name, age){
//继承属性
SuperType.call(this, name);
this.age = age;
}
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"Nicholas";
instance1.sayAge(); //29
var instance2 = new SubType("Greg", 27);
alert(instance2.colors); //"red,blue,green"
instance2.sayName(); //"Greg";
instance2.sayAge(); //27

In this example, the SuperType constructor defines two properties: name and colors. The prototype of SuperType defines a method sayName(). The SubType constructor passes in the name parameter when calling the SuperType constructor, and then defines its own attribute age. Then, the instance of SuperType is assigned to the prototype of SubType, and then the method sayAge() is defined on the new prototype. In this way, two different SubType instances can have their own properties - including the colors property, and can use the same method.

Combined inheritance avoids the shortcomings of prototype chains and borrowed constructors, combines their advantages, and becomes the most commonly used inheritance pattern in JavaScript. Furthermore, instanceof and isPrototypeOf() can also be used to identify objects created based on combined inheritance.

4. Prototypal inheritance

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

Inside the object() function, a temporary constructor is first created, then the passed in object is used as the prototype of this constructor, and finally a new instance of this temporary type is returned. Essentially, object() performs a shallow copy of the object passed into it. Consider the following example.

var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"

The prototypal inheritance advocated by Crockford requires that you must have an object that can serve as the basis of another object. If there is such an object, you can pass it to the object() function, and then modify the obtained object according to specific needs. In this example, the person object can be used as the basis for another object, so we pass it into the object() function, which then returns a new object. This new object uses person as its prototype, so its prototype contains a basic type value property and a reference type value property. This means that person.friends is not only owned by person, but also shared by anotherPerson and yetAnotherPerson. In effect, this is equivalent to creating two more copies of the person object.

ECMAScript 5 standardizes prototypal inheritance through the new Object.create() method. This method accepts two parameters: an object to be used as the prototype of the new object and (optionally) an object to define additional properties for the new object. The Object.create() method behaves the same as the object() method when one parameter is passed in.

var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
var yetAnotherPerson = Object.create(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"

The second parameter of the Object.create() method has the same format as the second parameter of the Object.defineProperties() method: each property is defined through its own descriptor. Any property specified in this way overrides the property of the same name on the prototype object. For example:

var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};

var anotherPerson = Object.create(person, {
name: {
value: "Greg"
}
});
alert(anotherPerson.name); //"Greg"

Browsers that support the Object.create() method include IE9, Firefox 4, Safari 5, Opera 12 and Chrome.

Prototypal inheritance is perfectly adequate when there is no need to go to great lengths to create a constructor, but you just want to keep one object similar to another object. But don't forget that properties containing reference type values ​​will always share the corresponding value, just like using the prototype pattern.

5. Parasitic inheritance

Parasitic inheritance is an idea closely related to prototypal inheritance, and was also popularized by Crockford. The idea of ​​parasitic inheritance is similar to the parasitic constructor and factory pattern, that is, creating a function just to encapsulate the inheritance process, which enhances the object in some way internally, and finally acts as if it really did all the work Return object. The following code demonstrates the parasitic inheritance pattern.

function createAnother(original){
var clone = object(original); //通过调用函数创建一个新对象
clone.sayHi = function(){ //以某种方式来增强这个对象
alert("hi");
};
return clone; //返回这个对象
}

In this example, the createAnother() function receives one parameter, which is the object that will be used as the basis for the new object. Then, pass this object (original) to the object() function and assign the returned result to clone. Then add a new method sayHi() to the clone object, and finally return the clone object. You can use the createAnother() function as follows:

var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = createAnother(person);
anotherPerson.sayHi(); //"hi"

这个例子中的代码基于person 返回了一个新对象——anotherPerson。新对象不仅具有person的所有属性和方法,而且还有自己的sayHi()方法。
在主要考虑对象而不是自定义类型和构造函数的情况下,寄生式继承也是一种有用的模式。前面示范继承模式时使用的object()函数不是必需的;任何能够返回新对象的函数都适用于此模式。

使用寄生式继承来为对象添加函数,会由于不能做到函数复用而降低效率;这一
点与构造函数模式类似。

6.寄生组合式继承

前面说过,组合继承是JavaScript 最常用的继承模式;不过,它也有自己的不足。组合继承最大的问题就是无论什么情况下,都会调用两次超类型构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数内部。没错,子类型最终会包含超类型对象的全部实例属性,但我们不得不在调用子类型构造函数时重写这些属性。再来看一看下面组合继承的例子。

function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name); //第二次调用SuperType()
this.age = age;
}
SubType.prototype = new SuperType(); //第一次调用SuperType()
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
alert(this.age);
};

加粗字体的行中是调用SuperType 构造函数的代码。在第一次调用SuperType 构造函数时,SubType.prototype 会得到两个属性:name 和colors;它们都是SuperType 的实例属性,只不过现在位于SubType 的原型中。当调用SubType 构造函数时,又会调用一次SuperType 构造函数,这一次又在新对象上创建了实例属性name 和colors。于是,这两个属性就屏蔽了原型中的两个同名属性。图6-6 展示了上述过程。
如图6-6 所示,有两组name 和colors 属性:一组在实例上,一组在SubType 原型中。这就是调用两次SuperType 构造函数的结果。好在我们已经找到了解决这个问题方法——寄生组合式继承。

所谓寄生组合式继承,即通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。其背后的基本思路是:不必为了指定子类型的原型而调用超类型的构造函数,我们所需要的无非就是超类型原型的一个副本而已。本质上,就是使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型。寄生组合式继承的基本模式如下所示。

function inheritPrototype(subType, superType){
var prototype = object(superType.prototype); //创建对象
prototype.constructor = subType; //增强对象
subType.prototype = prototype; //指定对象
}

这个示例中的inheritPrototype()函数实现了寄生组合式继承的最简单形式。这个函数接收两个参数:子类型构造函数和超类型构造函数。在函数内部,第一步是创建超类型原型的一个副本。第二步是为创建的副本添加constructor 属性,从而弥补因重写原型而失去的默认的constructor 属性。最后一步,将新创建的对象(即副本)赋值给子类型的原型。这样,我们就可以用调用inherit-Prototype()函数的语句,去替换前面例子中为子类型原型赋值的语句了,例如

function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function(){
alert(this.age);
};

这个例子的高效率体现在它只调用了一次SuperType 构造函数,并且因此避免了在SubType.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用instanceof 和isPrototypeOf()。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。

YUI 的YAHOO.lang.extend()方法采用了寄生组合继承,从而让这种模式首次出现在了一个应用非常广泛的JavaScript 库中。要了解有关YUI 的更多信息,请访问http://developer. yahoo.com/yui/。

以上所述就是本文的全部内容了,希望对大家学习javascript继承有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn