Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find where an object member is defined in Javascript?

Of course, most of the time, I can simply search for the identifier and look at all instances thereof. Often, searching for " =" or " :" will find the answer the fastest.

But this technique fails is situations like this:

// untested javascript:
function AddMemberToObject(object, value, memberName) {
    object[memberName] = value;
}

var myObj = {}

// 3,000 references to myObj

// ... somewhere else
var mysteryString = thisMethodCallsAnotherMethodCallsAnotherMethodEtc();

AddMemberToObject(myObj, someFunction, mysteryString);

// 3,000 more references to myObj

Let's say I haven't discovered the above code yet. As illustrated in this example, some things that make it hard to find where a member is defined include:

  • the object to add a member to being referenced many times
  • the name of the member being added is specified far away from where the member is added to the object. Worse yet, it may be dynamically generated, even generated on the server, in which case the member name will not appear in js source.

What are some techniques for finding where the member is added to the object in difficult cases like this? Is there a way to do this at runtime (e.g. make all additions to an object fire an event, which we can listen for and break on in the debugger)?

like image 888
jyoungdev Avatar asked Nov 04 '22 23:11

jyoungdev


1 Answers

Firefox features the non-standard function watch() which watches for a property to be assigned a value and runs a function when that occurs.

like image 134
HAL 9000 Avatar answered Nov 12 '22 12:11

HAL 9000