1 js原型继承
原理:原型继承只能是把要继承的属性或方法定义到构造函数的原型对象上
Child.prototype = new Perent()
Child.prototype.constructor = Child//保证继承的完整性
function A(name){ this.name = name } A.prototype.age = 10 function B(){ this.name = 'hh' } B.prototype = new A() var a = new B() console.log(a.age) console.log(a.name)
2. call继承
特点:只能继承父类的私有属性,不能继承父类的原型链上的属性,因为这个时候是将父类按照普通函数执行
function foo(name){ this.name = name } function C(){ foo.call(this,'gg') } var c = new C() console.log(c.name)
3. 寄生组合继承
其实就是原型链继承+ call继承
function foo(name){ this.name = name } foo.prototype.age = 20 function D(){ this.name = 'dd' } D.prototype = Object.create(foo.prototype)//关键 var d = new D() console.log(d.age)
ie8一下不兼容Object.create自己实现
Object.create = function(obj){ function oo(){} oo.prototype = obj return obj }
寄生组合继承另一种写法
function Foo(name){ this.name = name } Foo.prototype.age = 20 function E(){ Foo.call(this,'ee') } E.prototype = new Foo() E.prototype.constructor = E var e = new E()
4.es6中的继承
子类中constructor可以不用写,浏览器会默认添加,但是如果写了就必须写super()相当于call继承中的父类普通调用
class A { constructor(name){ this.name = name A.prototype.age = 20 } get(){ console.log(this.name+""this.age) } } class B extends A{ constructor(){ super('bb') } } var b = new B() b.name