Trash Can
Trash Can

Reputation: 6824

How to find the owner of a property in Javascript

Ok, because my initial question sounds unclear, so I decided to edit it. My question is how do you find out who defined a certain property, for example, the parseInt function, how do I know on which object it was definded like if parseInt was definded on the window object or the document object or whatever object it is? Thank you

I know the parseInt was definded the window object, I am just using it as an example in general, I am not specifically asking what object definded the parseInt property.

Also, please don't show me jQuery codes since I don't know jQuery that very good.

Upvotes: 4

Views: 3402

Answers (2)

Trash Can
Trash Can

Reputation: 6824

I know that to solve my question, we could use Object.prototype.hasOwnProperty(), but that would be very alot of typing because you have to type it out each time you need to know if a certain property is defined on a object. I have decided to write my own function to make this a little easier even though this is of no good practical use, I just wanted to satisfy my curiosity.

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

run this method

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
    }

Upvotes: 0

Travis J
Travis J

Reputation: 82297

There is unfortunately no way to determine using code what the variable environment is of a given variable.

As for object properties, they should be obvious if they are myObj.property. If not obvious, it could be possible to use an exhaustive search to look for their existence in certain places, or certain known recursively.

Overall, it is not possible to know without looking at implementation documentation.

Upvotes: 4

Related Questions