mikeorb wrote:
Is there a way to determine the object that a property is in? For
example:
By "property", you mean "method" (or Function) in your example.
function MyClass() { ... }
MyClass.prototype.myFunc = function() { ... }
var obj = new MyClass();
var sameobj = SOMEFUNCTION(obj.myFunc);
The example you give seems a little odd, in that you already have a
reference to "obj" in your variable name "obj", so why do you need a
function to get it again? Could you explain the application/context a
little more?
So my goal is to get a reference to the object by just having the
property.
For the purposes of this answer, I assume that you mean that if you
just pass a reference to "myFunc", can the receiving function guess
which instance of MyClass it came from. The answer is NO generally,
unless you use closures.
My answer is fairly amateur/simplified, so I hope it makes sense.
1 FUNCTIONS AS METHODS
In javascript, whenever you call a Javascript Function, it is always
being called as a "method" of some instance of an object.
You can discover which object is calling the function, through the
"this" keyword inside the function.
2 METHODS OF WINDOW OBJECT BY DEFAULT
The default is that a Function is called as a method of the "window"
object.
Thus:-
function MyFunction()
{
alert((this===window));
}
MyFunction(); // alerts true, "window" is implicit
window.MyFunction(); // explicit
window["MyFunction"](); // explicit
3. METHODS OF USER OBJECT
If you add a Function as a method of your own object, then the "this"
keyword will refer to the instance of that object, ONLY WHEN IT IS
CALLED AS A METHOD OF THAT OBJECT.
Thus:-
function MyClass(a)
{
this.a=a;
}
MyClass.prototype.myFunc=function(){return this;};
function fTest()
{
var inst=new MyClass(1);
var sameinst=inst.myFunc();
alert(sameinst.a);
}
However, if you get a reference to "myFunc" only, then "this" will
refer to the window object.
function fTest()
{
var inst=new MyClass(1);
var funcref=inst.myFunc;
alert((funcref()===window)); // true
}
4. CLOSURES
One way to achieve your goal may be to use closures. There are plenty
of posts in this news group on closures and scope chains if you search
it.
A closure is a means by which you can bind an externally declared
variable into a function. Effectively "global" variables are an
example of a closure at the top level of your script.
Thus:=
function MyClass(a)
{
var oInst=this; // oInst is effectively global to "myFunc"
this.a=a;
this.myFunc=function(){
return oInst;
}
}
function fTest()
{
var inst=new MyClass(1);
var funcref=inst.myFunc;
alert(funcref().a);
}
Hope this helps.