views:

79

answers:

3

I have the following JavaScript:

function b() {
    alert(arguments.caller[0]);
}

function X(x) {
    this.x = x;
}

X.prototype.a = function(i) {
    b();
}

new X(10).a(5);

This will show the message "5". However, I want to show "10", i.e. in the function b I want to access the "this" property of the caller. Is this possible, and how?

+1  A: 

You could pass the caller as an argument to the function:

function b(caller) {
    alert(caller.x);
};

function X(x) {
    this.x = x;
};

X.prototype.a = function(i) {
    b(this);
};

new X(10).a(5);

Note that arguments.caller is deprecated in JS 1.3 and removed in JS 1.5.

balpha
+1  A: 
function b() {
    alert(this.x);
}

function X(x) {
    this.x = x;
}

X.prototype.a = function(i) {
    b.call(this); /* <- call() used to specify context */
}

new X(10).a(5);
J-P
A: 

You are introducing a level of indirection by wrapping the call to function b inside an anonymous function. If possible, you should directly set it.

function b() {
  alert(this.x);  // 10
  alert(arguments[0]); // 5
}

function X(x) {
  this.x = x; /* alternatively, set this.x = arguments to capture all arguments*/
}

X.prototype.a = b;

new X(10).a(5);

Otherwise, you would need to pass the object, which can be done in either of the ways J-P or balpha suggested.

Jeff Meatball Yang