嵌套函数中“this”关键字的范围

Scope for "this" keyword in nested function?

本文关键字:关键字 范围 this 函数 嵌套      更新时间:2023-09-26

嗨,我的代码看起来像这样:

var myClass = {
    globalVar : {
        total : 100
    },
    myFunction : {
        getTotal : function() {
            return this.globalVar.total;
        }
    },
};
// Uncaught TypeError: Cannot read property 'total' of undefined 
alert(myClass.myFunction.getTotal() );

关键字 this 返回未定义,这是为什么?是因为我用var myClass而不是function myClass()吗?

谢谢

[编辑]这是 JSFiddle http://jsfiddle.net/DarcFiddle/cg7Fk/

这是

此时分配给myFunction的对象的范围。

正如Blender在评论中所说,这不是一个类。你想要的可能是这个:

var MyClass = function() {
    return {
        globalVar : {
            total : 100
        },
        getTotal : function() {
            return this.globalVar.total;
        }
    };
};
alert(new MyClass().getTotal() );

this结果是myFunction所以就像你在说myFunction.globalVar.total不存在。

如果需要,您可以像这样使其可重用。

function Food(cost) {
    this.getTotal = function () {
        return cost + (cost * 0.05); // add 5%
    };
}
var sandwich = new Food(2.50);
alert( sandwich.getTotal() ); // 2.625

http://jsfiddle.net/thetenfold/HvHxR/


有很多方法可以制作"类"(可以这么说)。
这不是唯一的方法,但这是一种体面的方法。