如何在Javascript中找到属性的所有者

时间:2014-12-22 23:36:39

标签: javascript properties

好的,因为我最初的问题听起来不太清楚,所以我决定编辑它。我的问题是你如何找出谁定义了某个属性,例如parseInt函数,我如何知道它被定义为哪个对象就像parseIntwindow上被定义一样对象或document对象或它是什么对象?谢谢

我知道parseInt被定义为window对象,我只是将它作为一般示例使用,我并没有具体询问什么对象定义parseInt属性。

另外,请不要向我展示jQuery代码,因为我不太了解jQuery。

2 个答案:

答案 0 :(得分:4)

遗憾的是,没有办法确定使用代码给定变量的变量环境。

对于对象属性,如果它们是myObj.property,它们应该是显而易见的。如果不是很明显,可以使用详尽的搜索来查找它们在某些地方的存在,或者某些已知的递归。

总的来说,如果不查看实施文档,就无法知道。

答案 1 :(得分:0)

我知道要解决我的问题,我们可以使用Object.prototype.hasOwnProperty(),但这会非常类型,因为每次你需要知道是否在对象上定义某个属性时你必须输入它。我已经决定编写自己的函数来使它变得更容易,即使这没有很好的实际用途,我只是想满足我的好奇心。

function findOwner(property, ownerObjectArray) {
    var result = []; // Array to store the objects that the given property is defined on

    for (var i = 1; i < arguments.length; i++)
    {
        var obj = arguments[i]; // the object currently being inspected
        var properyList= Object.getOwnPropertyNames(arguments[i]); // a list of all "Owned" properties by this object

        for (var j = 0; j < properyList.length; j++)
        {
            if (property === properyList[j]) result.push(obj.constructor);
        }
    }
                return result.length > 0 ? result : "undefinded";
} 

运行此方法

window.onload = run;

    function run()
    {
        alert(findOwner("parseInt", Array.prototype, window, document));    // passing 3 objects we want to test against to this method. It printed : [object Window], the given property "parseInt" was found on the "Window" object
    }