var A = {
x : function () { }
};
var b = function (method) {
//want to know method's "parent" here
};
b(A.x);
I want to know that x is defined in A when I call the b(A.x). Is this possible?
var A = {
x : function () { }
};
var b = function (method) {
//want to know method's "parent" here
};
b(A.x);
I want to know that x is defined in A when I call the b(A.x). Is this possible?
There's no nice built-in way to do this, because actually there are no methods in Javascript. They are independent Function objects that just happen to be assigned somewhere.
If you create new instance of function every time (e.g. closure) [thanks Matthew Crumley for pointing that out], then you can modify the function object to explicitly associate it with its parent:
x.parent = A;
and then you can call it properly as if it was a method:
x.call(x.parent);
Otherwise you will have to pass both function and its parent object.
Every function in JavaScript is actually a Function object.
<html>
<body>
<script>
var A = {
x: function (a_a, a_b) { alert(a_a + a_b); }
};
var b = function (a_method) {
alert(a_method.toString());
a_method.call(this, 1, 2);
};
b(A.x);
</script>
This question makes little sense from the perspective of the language as a function may exist on many objects.
var a = { name : 'a' },
b = { name : 'b' },
c = { name : 'c' };
a.x = function () { alert( this.name ); };
c.x = b.x = a.x; // a, b, and c all reference the same function
You may call the x
function with any context you want:
a.x(); // alerts "a" because "this" is object a
b.x(); // alerts "b" because "this" is object b
a.x.call( b ); // alerts "b" because "this" is object b (via parameter)
You can manipulate this behavior to work for you:
var b = function ( method ) {
// parent = this;
};
b.call( A, A.x );
There isn't however any way of knowing from inside a function what object it is assigned to as this isn't necessarily a single place.
Even adding a parent property won't work in all cases, because if the function is in the object's prototype, there is only one copy of the function object, so there's no way to tell which instance it came from. Here's an example to show the problem:
function MyClass() {
// Create a MyClass object
}
MyClass.prototype.x = function() { return 42; };
var a = new MyClass();
a.x.parent = a; // Set the parent to a
var b = new MyClass();
b.x.parent = b; // b.x and a.x both reference the same function from MyClass.prototype
Now, a.x.parent
and b.x.parent
are both set to b.
@porneL's method will work as long as each object gets its own copy of the function.
It's probably better to modify the function to take a parent object and a method so it will work with any function.