Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why is _objId undefined in this statement?: var _objId = self.id;

Status
Not open for further replies.

j0em0mma

Programmer
Jul 31, 2003
131
US
I have debugged this and verified that self.id evaluates to a scalar string that represents the name of the variable I assigned this object to...
 
Welcome to amateur hour, starring me. I was sending a parameter to my 'new object' call named 'id.' turns out that the 'id' I thought I was getting (the variable name stored in the window object associative array) was actually the one I was passing as a parameter.

This raises a question, though. Say I have the following:

Code:
var myObjInstance = new myCustomObj(param,...);

Is there a way to make a 'this' statement inside 'myCustomObj' object return the id/name of the variable it was assigned to without sending it through as a parameter? In other words, can I dynamically tell what the window object thinks 'this' is named from inside the object without first passing it?
 
I think maybe an explanation of how the 'this' keyword works will help you.

The 'this' keyword always refers to the context in which the function is being executed unless there is no valid context. In that case it uses the window object as the context.

So if you do this:
Code:
document.onclick = myObj.myMethod;
Any 'this' keyword in the function myMethod would refer to document because that is what is executing the function. To be accurate, in the example above we're actually making a copy of myMethod and assigning it as the onclick event handler.

To have the 'this' keyword refer to your custom object, you need to execute the function within the context of your custom object.
Code:
document.onclick = function(){ myObj.myMethod(); }
Now document is executing a generic function that tells your object to execute its method. Since the method is being called from your object, the 'this' keyword will now refer to the custom object.

Adam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top