How to find the owner of an object in Javascript

Good, because my initial question sounds unclear, so I decided to edit it. My question is how to find out who defined a particular property, for example, a function parseInt, how to find out on which object it was stopped, for example, if it parseIntwas stopped on an object windowor documentan object or any other object? Thanks you

I know that I parseIntwas tagged with an object window, I just use it as an example in general, I do not specifically ask which object had the property parseInt.

Also, please do not show me jQuery codes, since I do not know jQuery, which is very good.

+4
source share
2 answers

Unfortunately, there is no way to determine the environment variable of a given variable using code.

As for the properties of an object, they should be obvious if they are myObj.property. If this is not obvious, an exhaustive search could be used to search for their existence in certain places or some known recursively.

In general, it is impossible to find out without looking at the implementation documentation.

+4
source

, 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
    }
0

Source: https://habr.com/ru/post/1568683/


All Articles