Object.getPrototypeOf compatible polyfill implementation in javascript

How to get the prototype of an object.

Netscope and Firefox first gave an internal interface __proto__, and later other browsers also provided it.

But this is an internal interface.

Later ES5 stipulated a standard get method Object.getPrototypeOf.

 

Available through __proto__ in browsers that support __proto__.

In browsers before ie9, it cannot be obtained perfectly, but can be obtained through constructor.prototype,

The price is that you have to specify in the coding specification that you must not modify the constructor property of the object.

 

But the constructor property has to be changed in some cases.

such as inheritance.

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 in the above code

If not, cat.constructor will be Animal, if there is cat.constructor.prototype.constructor or Cat,

The effect we want is that Object.getPrototypeOf(cat) is Cat.prototype and Object.getPrototypeOf(Cat.prototype) is Animal.prototype.

So just constructor.prototype cannot be perfectly implemented,

We want to stipulate that when declaring a class, Cat.superclass=Animal must be added. Then the prototype can be obtained.

The final code is

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;
		};
	}
}

cost

The constructor cannot be arbitrarily changed,

Class inheritance must be written as follows

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();

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325629542&siteId=291194637