0

嗨,我的代码如下所示:

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返回undefined,这是为什么呢?是因为我使用var myClass而不是function myClass()

谢谢

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

4

3 回答 3

2

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

于 2013-10-07T04:28:35.980 回答
1

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

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

alert(new MyClass().getTotal() );
于 2013-10-07T04:28:51.863 回答
0

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/


有很多方法可以创建一个“类” (可以这么说)
这不是唯一的方法,但它是一个体面的方法。

于 2013-10-07T04:33:09.033 回答