How do you define an object that is a method?
There's no nice built-in way to do this because there are actually no methods in Javascript. They are independent function objects that are simply assigned somewhere.
If you create a new instance of the function every time (for example, close) [thanks to Matthew Crumley for pointing this out], you can modify the function object to explicitly associate it with its parent:
x.parent = A;
and then you can call it correctly as if it were a method:
x.call(x.parent);
Otherwise, you have to pass both the function and its parent.
source to share
This question doesn't make sense from a language point of view, since a function can 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 can call the function x
in 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 );
However, there is no way to know from within a function which object it is assigned to, since it doesn't have to be one place.
source to share
Even adding a parent property won't work in all cases, because if the function is in the prototype of the object, there is only one copy of the function object, so there is 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
both set to b.
The @porneL method will work as long as each object gets its own copy of the function.
It's probably better to change the function to take the parent object and method so that it works with any function.
source to share
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>
source to share