javascript检查对象原型
以下代码之间是否存在任何差异:javascript检查对象原型,javascript,prototype,Javascript,Prototype,以下代码之间是否存在任何差异: inst instanceof Constr 及 例如: var xyz = {} xyz instanceof Object 及 ??如果是,区别是什么,哪一个是首选的?\uuuuuu proto\uuuuu不是ECMAScript 5规范的一部分,您不能保证将来会支持它。访问对象原型的标准方法是访问构造函数的原型,或者更好(但这在IE8上不起作用) 检查构造函数的原型,但也“测试对象原型链中是否存在构造函数.prototype” 如果您的目标是检查某个对象
inst instanceof Constr
及
例如:
var xyz = {}
xyz instanceof Object
及
??如果是,区别是什么,哪一个是首选的?
\uuuuuu proto\uuuuu
不是ECMAScript 5规范的一部分,您不能保证将来会支持它。访问对象原型的标准方法是访问构造函数的原型,或者更好(但这在IE8上不起作用)
检查构造函数的原型,但也“测试对象原型链中是否存在构造函数.prototype”
如果您的目标是检查某个对象是否是特定类的实例,并且如果它不是直接实例对您来说没有问题,那么您应该使用
instanceof
操作符:它确实就是为此而设计的。instanceof进一步检查
var GrandParent=function(){};
var Parent = function(){}
Parent.prototype=new GrandParent()
var Child = function(){};
Child.prototype=new Parent()
var c=new Child();
console.log(c instanceof GrandParent);//true
console.log(c.__proto__ === GrandParent);//false
实际上还有第三种方法,看起来很像非标准的
\uuuuu proto\uuuu
示例:
Object.getPrototypeOf([]) === Array.prototype
厌倦:
console.log([] instanceof Object);//ture
console.log(Object.getPrototypeOf([]) === Object.prototype);//false
基本上,
instanceof
操作符检查整个原型链,其他方法不检查有两个区别。正如其他人之前提到的那样,的instanceof
是递归的。您可以实现自己版本的instanceof
,如下所示:
function instanceOf(obj, func) {
return Object.isPrototypeOf.call(func.prototype, obj);
}
此功能取决于该功能的可用性
第二个区别仅适用于浏览器。如中所述,instanceof
在浏览器中的实际实现如下:
function instanceOf(obj, func) {
var prototype = func.prototype;
while (obj = Object.getPrototypeOf(obj)) { //traverse the prototype chain
if (typeof object === "xml") //workaround for XML objects
return prototype === XML.prototype;
if (obj === prototype) return true; //object is instanceof constructor
}
return false; //object is not instanceof constructor
}
就这些。有关更多信息,请参见
instanceof
:的文档中的“浏览器中的实际实现”您再次指的是抽象伪代码,实际实现中没有实际实现会用到它:P@Esailija我现在不会费心在V8引擎中查找instanceof
的代码了,是吗=P
function instanceOf(obj, func) {
return Object.isPrototypeOf.call(func.prototype, obj);
}
function instanceOf(obj, func) {
var prototype = func.prototype;
while (obj = Object.getPrototypeOf(obj)) { //traverse the prototype chain
if (typeof object === "xml") //workaround for XML objects
return prototype === XML.prototype;
if (obj === prototype) return true; //object is instanceof constructor
}
return false; //object is not instanceof constructor
}