JavaScript对象返回空值

时间:2018-08-24 05:35:56

标签: javascript javascript-objects

此代码有什么问题?

function makeGamePlayer(int) {
    var bal = 0;
    var obj = {
        fun1: function () {
            bal += int;
        },
        fun2: function () {
            return bal;
        }
    };
    return obj;
}
console.log(makeGamePlayer(100)); //obj
console.log(makeGamePlayer(100).fun2());   //returning 0 but expecting the 100

我尝试运行上面的代码,但没有得到正确的结果。我需要一些帮助。

谢谢。

2 个答案:

答案 0 :(得分:3)

唯一使第二个console.log输出100 而无需更改makeGamePlayer代码的方法如下

function makeGamePlayer(int) {
    var bal = 0;
    var obj = {
        fun1: function () {
            bal += int;
        },
        fun2: function () {
            return bal;
        }
    };
    return obj;
}

// commented, as it's irrelevant
//console.log(makeGamePlayer(100)); //obj

var x = makeGamePlayer(100); // x is a **different obj and bal by the way**
x.fun1();
console.log(x.fun2()); 

// to illustrate that each time you call `makeGamePlayer` you get a new obj and a new bal

var y = makeGamePlayer(1000);
y.fun1();
// note, this is STILL 100
console.log(x.fun2()); 
// this outputs 1000
console.log(y.fun2()); 
// output
// 100
// 100
// 1000

答案 1 :(得分:-2)

您正在fun1函数中递增int,但是您尚未在任何地方调用。您调用了fun2函数,该函数将按原样返回bal。