In the previous article, I introduced the concept of prototype and learned about the relationship between the three good friends of constructor, prototype object and instance in JavaScript: each constructor has a "patron saint"—— The prototype object also has a "position" of the constructor in its heart, and they are in love with each other, but the instance "secretly loves" the prototype object, and she also retains a position of the prototype object in her heart.
Javascript itself is not an object-oriented language, but an object-based language. For people who are used to other OO languages, it is a little uncomfortable at first, because there is no concept of "class" here, or "class" and "class" There is no distinction between "instances", let alone "parent classes" and "subclasses". So, how are these objects in JavaScript so connected?
Fortunately, JavaScript has provided the implementation of "inheritance" from the beginning of its design. Before understanding "inheritance", let's first understand the concept of prototype chain.
Prototype Chain
We know that the prototype has a pointer to the constructor. What if we make the SubClass prototype object equal to another type instance new SuperClass()? At this time, the SubClass prototype object contains a pointer to the SuperClass prototype, and the SuperClass prototype also contains a pointer to the SuperClass constructor. . . In this way, layer by layer, a prototype chain is formed.
The specific code is as follows:
function SuperClass(){ this.name = "women" } SuperClass.prototype.sayWhat = function(){ return this.name + ":i`m a girl!"; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); SubClass.prototype.subSayWhat = function(){ return this.subname + ":i`m a beautiful girl"; } var sub = new SubClass(); console.log(sub.sayWhat());//women:i`m a girl!
Use prototype chain to implement inheritance
It can be seen from the above code that SubClass inherits the properties and methods of SuperClass. This inheritance is implemented by assigning the instance of SuperClass to the prototype object of SubClass, so that the prototype object of SubClass is overwritten by an instance of SuperClass. It has all its properties and methods, and also has a pointer to the SuperClass prototype object.
There are some things we need to pay attention to when using the prototype chain to implement inheritance:
Pay attention to the changes in constructor after inheritance. The constructor of sub here points to SuperClass, because the prototype of SubClass points to the prototype of SuperClass. When understanding the prototype chain, don't ignore the default Object object at the end. This is why we can use built-in methods such as toString in all objects.
When implementing inheritance through the prototype chain, you cannot use literals to define prototype methods, because this will overwrite the prototype object (also introduced in the previous article):
function SuperClass(){ this.name = "women" } SuperClass.prototype.sayWhat = function(){ return this.name + ":i`m a girl!"; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); SubClass.prototype = {//此处原型对象被覆盖,因为无法继承SuperClass属性和方法 subSayWhat:function(){ return this.subname + ":i`m a beautiful girl"; } } var sub = new SubClass(); console.log(sub.sayWhat());//TypeError: undefined is not a function
Instance sharing problem. When explaining prototypes and constructors earlier, we have introduced that prototypes containing reference type attributes will be shared by all instances. Similarly, the prototypes we inherit will also share the reference type attributes in the "parent class" prototype. When After we modify the reference type attributes of the "parent class" through prototypal inheritance, all other instances inherited from the prototype will be affected. This is not only a waste of resources, but also a phenomenon we don't want to see:
function SuperClass(){ this.name = "women"; this.bra = ["a","b"]; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); var sub1 = new SubClass(); sub1.name = "man"; sub1.bra.push("c"); console.log(sub1.name);//man console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub1.name);//woman console.log(sub2.bra);//["a","b","c"]
Note: When an element is added to the array here, all instances inherited from SuperClass will be affected, but if the name attribute is modified, it will not affect other instances. This is because the array is a reference type and name is basic. type.
How to solve the problem of instance sharing? Let’s look down...
Classic inheritance (constructor stealing)
Just as we have introduced that prototypes are rarely used alone to define objects, in actual development we rarely use prototype chains alone. In order to solve the problem of sharing reference types, JavaScript developers have introduced the classic inheritance model (also known as For borrowed constructor inheritance), its implementation is simply to call the supertype constructor in the subtype constructor. We need to use the call() or apply() function provided by javascript. Let’s take a look at the example:
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } function SubClass() { this.subname = "your sister"; //将SuperClass的作用域赋予当前构造函数,实现继承 SuperClass.call(this); } var sub1 = new SubClass(); sub1.bra.push("c"); console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub2.bra);//["a","b"]
SuperClass.call(this); This sentence means that the initialization work of the SuperClass constructor is called in the instance (context) environment of SubClass, so that each instance will have its own copy of the bra attribute. , have no influence on each other.
However, this implementation is still not perfect. Since the constructor is introduced, we are also faced with the problem of the constructor mentioned in the previous article: if there is a method definition in the constructor, then for no instance There is a separate Function reference. Our purpose is to share this method, and the methods we define in the supertype prototype cannot be called in subtype instances:
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function(){ console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); } var sub1 = new SubClass(); console.log(sub1.sayWhat());//TypeError: undefined is not a function
如果你看过上篇文章关于原型对象和构造函数的,想必你已经知道解决这个问题的答案了,那就是沿用上篇的套路,使用“组合拳”!
组合式继承
组合式继承就是结合原型链和构造函数的优势,发出各自特长,组合起来实现继承的一种方式,简单来说就是使用原型链继承属性和方法,使用借用构造函数来实现实例属性的继承,这样既解决了实例属性共享的问题,也让超类型的属性和方法得到继承:
function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function(){ console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); //第二次调用SuperClass } SubClass.prototype = new SuperClass(); //第一次调用SuperClass var sub1 = new SubClass(); console.log(sub1.sayWhat());//hello
组合继承的方式也是实际开发中我们最常用的实现继承的方式,到此已经可以满足你实际开发的需求了,但是人对完美的追求是无止境的,那么,必然会有人对这个模式“吹毛求疵”了:你这个模式调用了两次超类型的构造函数耶!两次耶。。。你造吗,这放大一百倍是多大的性能损失吗?
最有力的反驳莫过于拿出解决方案,好在开发者找到了解决这个问题的最优方案:
寄生组合式继承
在介绍这个继承方式前,我们先了解下寄生构造函数的概念,寄生构造函数类似于前面提到的工厂模式,它的思想是定义一个公共函数,这个函数专门用来处理对象的创建,创建完成后返回这个对象,这个函数很像构造函数,但构造函数是没有返回值的:
function Gf(name,bra){ var obj = new Object(); obj.name = name; obj.bra = bra; obj.sayWhat = function(){ console.log(this.name); } return obj; } var gf1 = new Gf("bingbing","c++"); console.log(gf1.sayWhat());//bingbing
寄生式继承的实现和寄生式构造函数类似,创建一个不依赖于具体类型的“工厂”函数,专门来处理对象的继承过程,然后返回继承后的对象实例,幸运的是这个不需要我们自己实现,道哥(道格拉斯)早已为我们提供了一种实现方式:
function object(obj) { function F() {} F.prototype = obj; return new F(); } var superClass = { name:"bingbing", bra:"c++" } var subClass = object(superClass); console.log(subClass.name);//bingbing
在公共函数中提供了一个简单的构造函数,然后将传进来对象的实例赋予构造函数的原型对象,最后返回该构造函数的实例,很简单,但疗效很好,不是吗?这个方式被后人称为“原型式继承”,而寄生式继承正是在原型式基础上,通过增强对象的自定义属性实现的:
function buildObj(obj){ var o = object(obj); o.sayWhat = function(){ console.log("hello"); } return o; } var superClass = { name:"bingbing", bra:"c++" } var gf = buildObj(superClass); gf.sayWhat();//hello
寄生式继承方式同样面临着原型中函数复用的问题,于是,人们又开始拼起了积木,诞生了——寄生组合式继承,目的是解决在指定子类型原型时调用父类型构造函数的问题,同时,达到函数的最大化复用。基于以上基础实现方式如下:
//参数为两个构造函数 function inheritObj(sub,sup){ //实现实例继承,获取超类型的一个副本 var proto = object(sup.prototype); //重新指定proto实例的constructor属性 proto.constructor = sub; //将创建的对象赋值给子类型的原型 sub.prototype = proto; } function SuperClass() { this.name = "women"; this.bra = ["a", "b"]; } SuperClass.prototype.sayWhat = function() { console.log("hello"); } function SubClass() { this.subname = "your sister"; SuperClass.call(this); } inheritObj(SubClass,SuperClass); var sub1 = new SubClass(); console.log(sub1.sayWhat()); //hello
这个实现方式避免了超类型的两次调用,而且也省掉了SubClass.prototype上不必要的属性,同时还保持了原型链,到此真正的结束了继承之旅,这个实现方式也成为了最理想的继承实现方式!人们对于javascript的继承的争议还在继续,有人提倡OO,有人反对在javascript做多余的努力去实现OO的特性,管他呢,至少又深入了解了些!