繁体   English   中英

函数参数的JavaScript执行上下文

[英]JavaScript execution context of function argument

function Apple(){
    this.name="apple";
}
function Orange(){
    this.name="orange";

    this.apple = new Apple();
    this.apple.onCalled=function(){
        alert(this.name);
    }
}
Orange.prototype.onCalled=function(){
    this.apple.onCalled();
}
var orange = new Orange();
orange.onCalled();

当前代码显示为“ apple”。 如何修改“ this.apple.onCalled = function()”行,使其显示为“橙色”?

即我想将一个函数传递给另一个对象,但是当调用该函数时,访问传递该函数的对象的变量,而不是执行该函数的对象的变量。 一个明显的解决方案是使用全局变量(例如orange.name),但是我正在寻找一种更好的方法,因为有很多对象,并且我不想全局化所有内容。

使用闭包。

function Orange(){
    this.name="orange";

    this.apple = new Apple();
    var that = this;
    this.apple.onCalled=function() {
        alert(that.name);
    }
}

有一个读怎么关键字this作品在JS,这是一个有点棘手,但很容易掌握。

您可以这样写:

Orange.prototype.onCalled=function(){
    this.apple.onCalled.call(this);
}

很难给出一个普遍的答案。 要了解的是, this绑定在任何函数调用上。 可以通过callapply函数或通过显式控制. 访问函数作为对象的属性时的运算符。

科斯给出的使用闭包的答案可能也很重要。 这取决于您想要的效果。

Orange.prototype.onCalled=function(){
    this.apple.onCalled.call(this);
}

示例: http//jsfiddle.net/XrtZe/

看看: JavaScript的范围

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM