如何获取一个对象的原型。
netscope和火狐最早给了一个内部接口__proto__,后来别的浏览器也提供了。
但是这是一个内部接口。
后来ES5规定了一个标准的获取方法Object.getPrototypeOf。
在支持__proto__的浏览器中可以通过__proto__得到。
在ie9以前的浏览器中,无法完美获取,可以通过constructor.prototype获取,
代价是你必须在编码规范里规定,不得修改对象的constructor属性。
但是constructor属性,在一些情况下不得不改。
比如说继承。
function Animal(){
}
Animal.prototype.say=function(){
alert("啊");
};
//声明一个子类
function Cat(){
}
Cat.prototype=Object.create(Animal.prototype);//继承Animal
Cat.prototype.constructor=Cat;
Cat.prototype.say=function(){
alert("喵");
};
var cat=new Cat();
上面代码中的Cat.prototype.constructor=Cat
如没有的话cat.constructor就会是Animal,有的话cat.constructor.prototype.constructor还是Cat,
我们想要的效果是Object.getPrototypeOf(cat)是Cat.prototype,Object.getPrototypeOf(Cat.prototype)是Animal.prototype。
所以仅仅constructor.prototype是无法完美实现的,
我们要规定声明类时必须加上Cat.superclass=Animal。然后才能获取到原型。
最终的代码是
if(!Object.getPrototypeOf){
if('__proto__' in {}){
Object.getPrototypeOf=function(object){
return object.__proto__;
};
}else{
Object.getPrototypeOf=function(object){
var constructor=object.constructor;
if(object!=constructor.prototype){
return constructor.prototype;
}else if('superclass' in constructor){
return constructor.superclass.prototype;
}
console.warn("cannot find Prototype");
return Object.prototype;
};
}
}
代价
constructor不能随便乱改,
类继承必须按照下面的写法
function Animal(){
}
Animal.prototype.say=function(){
alert("啊");
};
//声明一个子类
function Cat(){
}
Cat.prototype=Object.create(Animal.prototype);//继承Animal
Cat.superclass=Animal;//为了其他程序的代码方便获取父类
Cat.prototype.constructor=Cat;
Cat.prototype.say=function(){
alert("喵");
};
var cat=new Cat();