检查对象是否具有用户定义的原型? [英] Check if an object has a user defined prototype?

查看:47
本文介绍了检查对象是否具有用户定义的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地说,我可以检查一个对象是否有用户定义的原型吗?

Simply put can I check if an object has a user defined prototype?

示例;

var A = function() {};

var B = function() {};

B.prototype = {

};

// Pseudocode
A.hasUserPrototype(); // False
B.hasUserPrototype(); // True

这可能吗?

推荐答案

假设你想知道一个对象是否是自定义构造函数的实例,你可以将它的原型与 Object.prototype:

Assuming you want to find out whether an object is an instance of a custom constructor function, you can just compare its prototype against Object.prototype:

function hasUserPrototype(obj) {
    return Object.getPrototypeOf(obj) !== Object.prototype;
}

或者如果你正确维护了 constructor 属性:

Or if you maintain the constructor property properly:

function hasUserPrototype(obj) {
    return obj.constructor !== Object;
}

这也适用于不支持 Object.getPrototypeOf 的浏览器.

This would also work in browsers which don't support Object.getPrototypeOf.

但是对于其他本机对象,例如函数、正则表达式或日期,这两种解决方案都会返回 true.要获得更好"的解决方案,您可以将原型或构造函数与所有原生原型/构造函数进行比较.

But both solutions would return true also for other native objects, like functions, regular expressions or dates. To get a "better" solution, you could compare the prototype or constructor against all native prototypes/constructors.

更新:

如果你想测试一个函数是否有用户定义的prototype值,那么恐怕没有办法检测到这一点.初始值只是一个具有特殊属性(constructor)的简单对象.你可以测试这个属性是否存在(A.prototype.hasOwnProperty('constructor')),但如果设置原型的人做对了,他们会正确地添加更改原型后的 constructor 属性.

If you want to test whether a function has a user defined prototype value, then I'm afraid there is no way to detect this. The initial value is just a simple object with a special property (constructor). You could test whether this property exists (A.prototype.hasOwnProperty('constructor')), but if the person who set the prototype did it right, they properly added the constructor property after changing the prototype.

这篇关于检查对象是否具有用户定义的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆