ES5中的继承 1.JAVASCRIPT中的继承,不是真正意义上的面向对象继承,而是JS中特有的,和面向对象继承有点区别的,就是js的原型 2.利用构造函数 缺陷:不能继承原型的方法 解决:字类的prototype等于基类的实例(还是有一些缺点的)
//利用构造函数,但是无法继承父类原型上的方法 function P(){ this.name = 'parent' this.say = function(){ console.log('咕咕') } } P.prototype.test = function(){ console.log('yuanxing') } function C(){ P.call(this); this.name = 'child' this.age = 11 } var child = new C(); child.say(); child.test(); //报错
接上。把C的prototype变成P的一个实例,
function P(){ this.name = 'parent' this.say = function(){ console.log('咕咕') } } P.prototype.test = function(){ console.log('yuanxing') } function C(){ //在构造函数C的内部,执行了P.call(this)这句代码,改变了P构造函数内部的this指向,实现C继承P的属性和方法,P拥有的同名属性会被C替换了。 P.call(this); this.name = 'child' this.age = 11 } //因为P的实例可以访问到P的prototype, C.prototype = new P(); var child = new C(); child.say(); child.test();