面向对象实现方法:基于类,基于原型,基于元类
JS采用基于原型(prototype-based):
读遍历:对实例进行写操作时,会为实例建立相应成员表;读操作时,若找不到相应属性,则遍历原型链直到找到或返回undefined为止。
新建函数时:
function F(){};实际发生了:1.为该函数(F)添加prototype属性;
2.为prototype对象添加constructor属性,并使其指向F;
此时若用构造器创建实例f:
var f=new F();alert(f.constructor===F);//true
原型链的一个问题:function A(){};
function B(){};
B.prototype=new A();
var b=new B();
alert(b.constructor===A);此时访问b的constructor属性=>遍历原型链=>找到原型(new A()对象)=>访问new A()的constructor属性=>遍历原型链=>找到原型A.prototype=>访问A.prototype.constructor=>取得A故alert(b.constructor===A)为true
。。。。。。。。雾。。。。。。。。。。。。。。。。。。。
本文解析了JavaScript中基于原型的对象实现方式,介绍了函数创建时如何自动添加prototype属性及constructor属性指向,探讨了通过构造函数创建实例的过程及原型链查找机制。
4710

被折叠的 条评论
为什么被折叠?



