本文是面向对象第三部分--继承,相对于前两个,篇幅过长,理解稍微难点,不过多思考多敲敲,会一下子茅塞顿开,就懂了,不太懂面向对象-创建对象的,可以看这篇文章,
新增AI编程课程,引领技术教育新趋势
function Animal(){ this.type = 'animal'; } Animal.prototype.feature = function(){ alert(this.type); } function Cat(name,color){ this.name = name; this.color = color; } Cat.prototype = new Animal(); var tom = new Cat('tom','blue'); console.log(tom.name); // 'tom' console.log(tom.color); // 'blue' console.log(tom.type); // 'animal' tom.feature() // 'animal' 这个例子中有创建了两个构造函数,Animal构造函数有一个type属性和feature方法。Cat构造函数有两个属性:name和color。实例化了一个Animal对象,并且挂载到了Cat函数的原型上,相当于重写了Cat的原型,所以Cat函数拥有Animal函数的所有属性和方法。
然后又Cat函数new出一个tom对象,tom对象拥有Cat函数的属性和方法,因此也拥有Animal的属性和方法。
通过上面的例子,可以总结:通过改变构造函数的原型,进而实现继承。
ps:
1 如果在继承原型对象之前,产生的实例,其内部指针还是只想最初的原型对象。
function Animal(){ this.type = 'animal'; } Animal.prototype.feature = function(){ alert(this.type); } function Cat(name,color){ this.name = name; this.color = color; } Cat.prototype.type = 'cat'; Cat.prototype.feature = function(){ alert(this.type); } var tom = new Cat('tom','blue'); Cat.prototype = new Animal();// 先实例化对象,再重写原型,结果指针还是指向最初的原型 console.log(tom.name); // 'tom' console.log(tom.color); // 'blue' console.log(tom.type); // 'cat' ----- 是最初的type tom.feature() // 'cat'从打印结果来看:new出来的tom对象,在Cat.prototype重写原型之后,依然还是指向没重写的原型上。
2 在通过原型链实现继承时,不能使用对象字面量创建原型方法。因为这样做就会重写原型链。
function Animal(){ this.type = 'animal'; this.size = 'small' } Animal.prototype.feature =