javascript基于原型链实现继承,重在理解__proto__,prototype,constructor之间的关系。
先试着读一下这段代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function Parent() { this.name = "xiaoming"; } Parent.prototype.getName = function() { return this.name; }; function Child() { Parent.apply(this); this.age = 18; } function inherit(parentClass, childClass) { var F = function() {} F.prototype = parentClass.prototype; childClass.prototype = new F(); childClass.prototype.constructor = childClass; } inherit(Parent, Child); Child.prototype.getAge = function() { return this.age; } var child = new Child(); console.log(child); console.log(child instanceof Child); console.log(child instanceof Parent); |
这段代码实现了Child继承Parent,下面分析一下。
一般来说,类对象是通过一个构造函数创建的,类对象共享的属性/函数应该放在prototype里,非共享的则随着构造函数赋值给this(也就是当前构造的对象)。
既然Child要继承Parent,那么一方面需要继承Parent的原型里的共享属性/函数,另外一方面需要继承Parent构造函数里赋值给当前对象的属性。同时,Child的构造函数也会赋值this一些新的属性,Child也需要在自己的原型对象上定义若干的共享属性/函数。
上面的代码给出了一个合适的思路:
- Child的构造函数中调用Parent构造函数,将this传入从而赋值得到Parent的属性。
- Child的原型中找不到的共享属性/函数,应该继续在Parent的原型中寻找。
遵循这样的思路,最终一次对child对象的访问将是这样的过程:
在child对象中查找 -> 在child的prototype中查找(new F()) -> 在parent的prototype中查找(是由于F的prototype==parent.prototype)。
听说ES5的object.create方法就是类似实现。
js大法好。
如果文章帮助您解决了工作难题,您可以帮我点击屏幕上的任意广告,或者赞助少量费用来支持我的持续创作,谢谢~

👍