函数参数的 JavaScript 执行上下文

JavaScript execution context of function argument

本文关键字:执行 上下文 JavaScript 参数 函数      更新时间:2023-09-26
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();

目前代码显示"苹果"。如何修改"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函数显式控制,也可以在访问作为对象属性的函数时由.运算符显式控制。

Kos给出的关于使用闭包的答案也可能是相关的;这取决于你想要的效果。

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

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

看看: JavaScript 中的范围