简体   繁体   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();

Currently the code shows "apple". 当前代码显示为“ apple”。 How can I modify the "this.apple.onCalled=function()" line so that it shows "orange"? 如何修改“ this.apple.onCalled = function()”行,使其显示为“橙色”?

ie I want to pass a function to another object, but when that function is called, access variables of the object who passed the function, not the variables of the object who is executing the function. 即我想将一个函数传递给另一个对象,但是当调用该函数时,访问传递该函数的对象的变量,而不是执行该函数的对象的变量。 An obvious solution would be to use global variables (eg orange.name) but I'm looking for a better way because there are many objects and I don't want to global everything. 一个明显的解决方案是使用全局变量(例如orange.name),但是我正在寻找一种更好的方法,因为有很多对象,并且我不想全局化所有内容。

Use a closure. 使用闭包。

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

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

Have a read how keyword this works in JS, it's a bit tricky but easy to grasp. 有一个读怎么关键字this作品在JS,这是一个有点棘手,但很容易掌握。

You could write: 您可以这样写:

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

It's hard to give a general answer. 很难给出一个普遍的答案。 The thing to understand is that this is bound upon any function call. 要了解的是, this绑定在任何函数调用上。 That can be explicitly controlled with the call or apply functions, or by the . 可以通过callapply函数或通过显式控制. operator when accessing a function as a property of an object. 访问函数作为对象的属性时的运算符。

The answer Kos gives about using a closure may also be relevant; 科斯给出的使用闭包的答案可能也很重要。 it depends on the effect you want. 这取决于您想要的效果。

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

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

Have a look at: Scope in JavaScript 看看: JavaScript的范围

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

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