js中常用的两种继承 : 原型链继承 跟 类式继承(构造函数继承) 拓展:instanceof() 判断实例属于哪类 isPrototyof()判断子类是否是当前原型链中派生的实例
1.类式继承 在子类中调用父类改变父类指向实现继承
function Super(){ this.colors=["red","blue"]; } function Sub(){ Super.call(this); }
2.原型链继承 将父类的实例赋值给子类
<script> function Parent(){ this.name = ‘mike‘; } function Child(){ this.age = 12; } Child.prototype = new Parent();//Child继承Parent,通过原型,形成链条 var test = new Child(); alert(test.age); alert(test.name);//得到被继承的属性 //继续原型链继承 function Brother(){ //brother构造 this.weight = 60; } Brother.prototype = new Child();//继续原型链继承 var brother = new Brother(); alert(brother.name);//继承了Parent和Child,弹出mike alert(brother.age);//弹出12 </script>
3.原型链继承有两个问题 意识字面量重写原型会中断关系 而是无法传参所以我们借用 原型链加类式继承 的模式(之组合模式),但是组合模式中的父类会被调用两次,所以可以用下面的寄生组合式继承
<script>
function Parent(age){
this.name = [‘mike‘,‘jack‘,‘smith‘];
this.age = age;
}
Parent.prototype.run = function () {
return this.name + ‘ are both‘ + this.age;
};
function Child(age){
Parent.call(this,age);//对象冒充,给超类型传参
}
Child.prototype = new Parent();//原型链继承 //Child.prototype = Object.create(parent.prototype);
var test = new Child(21);//写new Parent(21)也行
alert(test.run());//mike,jack,smith are both21
</script>
4.原型式继承 借助原型并基于已有的对象创建新对象 ,同时还不用创建自定义类型的方式
<script> function obj(o){ function F(){} F.prototype = o; return new F(); } var box = { name : ‘trigkit4‘, arr : [‘brother‘,‘sister‘,‘baba‘] }; var b1 = obj(box); alert(b1.name);//trigkit4 b1.name = ‘mike‘; alert(b1.name);//mike alert(b1.arr);//brother,sister,baba b1.arr.push(‘parents‘); alert(b1.arr);//brother,sister,baba,parents var b2 = obj(box); alert(b2.name);//trigkit4 alert(b2.arr);//brother,sister,baba,parents </script> //首先在obj函数的内部创建一个临时性的构造函数,然后将传入的对象作为这个构造函数的原型,最后返回这个临时类型的新实例
5,寄生式继承(原型式+工厂模式)
<script> function create(o){ var f= obj(o); f.run = function () { return this.arr;//同样,会共享引用 }; return f; } </script>
6.寄生组合式继承
<script> function obj(o){ function F(){} F.prototype = o; return new F(); } function create(parent,test){ var f = obj(parent.prototype);//创建对象 f.constructor = test;//增强对象 } function Parent(name){ this.name = name; this.arr = [‘brother‘,‘sister‘,‘parents‘]; } Parent.prototype.run = function () { return this.name; }; function Child(name,age){ Parent.call(this,name); this.age =age; } inheritPrototype(Parent,Child);//通过这里实现继承 var test = new Child(‘trigkit4‘,21); test.arr.push(‘nephew‘); alert(test.arr);// alert(test.run());//只共享了方法 var test2 = new Child(‘jack‘,22); alert(test2.arr);//引用问题解决 </script>
原文:https://www.cnblogs.com/wildccy/p/10499483.html