我有以下 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”属性。这可能吗,怎么做?
我有以下 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 中被删除。
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);
您通过将对函数 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);
否则,您需要传递对象,这可以通过 JP 或 balpha 建议的任何一种方式来完成。