对象创建:
当一个函数对象被创建时候,function构造器产生的函数对象会运行类似这样的代码:
this.prototype={constructor:this};
假设函数f
f用new方式构造对象时,对象的constructor被设置成这个f.prototype.constructor
如果函数在创建对象前修改了函数的prototype,会影响创建出来对象的construtor属性
如:
function f(){};
f.prototype={constructor:'1111'};
var o=new f();//o.constructor===‘1111’ true
继承原理:
javascript中的继承是使用原型链的机制,每个函数的实例都共享构造函数prototype属性中定义的数据,要使一个类继承另一个,需要把父函数实例赋值到子函数的prototype属性。并且在每次new实例对象时,对象的私有属性__proto__会被自动连接到构造函数的prototype。
instanceof就是查找实例对象的私有prototype属性链来确定是否是指定对象的实例
具体实例:
//instanceof实现
function myinstanceof(obj,type)
{
var proto=obj.__proto__;
while(proto)
{
if(proto ===type.prototype)break;
proto=proto.__proto__;
}
return proto!=null;
}
function view(){}
function treeview(){}
treeview.prototype=new view();//treeview.prototype.__proto__=treeview.prototype 自动完成
treeview.prototype.constructor=treeview;//修正constructor
var view=new treeview();//view.__proto__=treeview.prototype 自动完成
alert(view instanceof view); //true 查找到view.__proto__.__proto__时找到
alert(view instanceof treeview); //true 查找到view.__proto__时找到
alert(myinstanceof(view,view)); //true
alert(myinstanceof(view,treeview)); //true
上面自定义的myinstanceof就是自己实现的一个instanceof功能的函数,由于ie内核实例存储prototype不是__proto__,所以myinstanceof会无法通过,其他浏览器上应该都没有问题