javascript - 函数调用 javascript 中的 "this"

标签 javascript function this

// Situation 1 
var a = function A() { 
    this.x = 1;
    var b = function B () {
        this.x = 2;
        console.log('Method B : x = ' + this.x);
    };
    console.log('Method A : x = ' + this.x);
    b();
}

当我调用 a() 时,我的结果是

Method A : x = 1
Method B : x = 2

但是如果我删除“this.x = 2”:

// Situation 2
var a = function A() { 
    this.x = 1;
    var b = function B () {
        console.log('Method B : x = ' + this.x);
    };
    console.log('Method A : x = ' + this.x);
    b();
}

我的结果是

Method A : x = 1
Method B : x = 1

不明白为什么

  • 情况 2:函数 B 的“this”引用函数 A 的“this”

但是

  • 情况 1:在函数 B 中赋值“this.x = 2”时,函数 A 的“this.x”没有改变

我的代码在 Chrome v23 上运行

最佳答案

由于 this.x = 2 位于函数 B 的定义中,因此只有在调用 B 时(而不是定义它时),它才会发生。尝试这个版本并查看:

// Situation 3
var a = function A() { 
    this.x = 1;
    var b = function B () {
        this.x = 2;
        console.log('Method B : x = ' + this.x);
    };
    console.log('Method A before B: x = ' + this.x);
    b();
    console.log('Method A after B: x = ' + this.x);
}

关于javascript - 函数调用 javascript 中的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999660/

相关文章:

javascript - 尝试在点击事件中创建点击事件但未获得所需结果

javascript - 无法访问 angular.js View 中的数组项

javascript - 如果当前值不是数组中的值,则打印文本

javascript - 如何将用户选择的酒店房间乘以入住天数?

c++ - 调用基类的构造函数时隐式 'this'

javascript - 为什么 "$.ajax({"会刷新?

javascript - 将变量放在双引号之间

c - 如何使用Goto功能

android - 这个/扩展上下文?

java - 这个关键字及其工作原理