Javascript 访问';这';调用堆栈中较高的方法中的对象

Javascript 访问';这';调用堆栈中较高的方法中的对象,javascript,callstack,Javascript,Callstack,我有以下JavaScript: function b() { alert(arguments.caller[0]); } function X(x) { this.x = x; } X.prototype.a = function(i) { b(); } new X(10).a(5); 这将显示消息“5”。但是,我想显示“10”,即在函数b中,我想访问调用者的“this”属性。这是否可能,以及如何将调用者作为参数传递给函数: function b(caller)

我有以下JavaScript:

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

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

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

new X(10).a(5);

这将显示消息“5”。但是,我想显示“10”,即在函数b中,我想访问调用者的“this”属性。这是否可能,以及如何将调用者作为参数传递给函数:

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

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

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

new X(10).a(5);
请注意,arguments.caller在JS 1.3中被弃用,在JS 1.5中被删除。

函数b(){
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);
警报(this.x); } 函数X(X){ 这个.x=x; } X.prototype.a=函数(i){
b、 调用(this);/*通过将对函数b的调用包装在匿名函数中,您引入了一个间接级别。如果可能,您应该直接设置它

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);
否则,您需要传递对象,这可以通过J-p或balpha建议的任何一种方式完成