【问题标题】:JavaScript object returning null value [closed]JavaScript对象返回空值[关闭]
【发布时间】:2018-08-24 05:35:56
【问题描述】:

这段代码有什么问题?

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

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

提前致谢。

【问题讨论】:

  • 你从来没有打电话给fun1
  • 但是 bal 是一个全局变量,它应该返回 100 对
  • 不,它不是全局的并且你永远不会在任何地方添加任何东西,因为你永远不会调用 fun1

标签: javascript javascript-objects


【解决方案1】:

使第二个 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

【讨论】:

    【解决方案2】:

    你在 fun1 函数中递增 int,但你没有在任何地方调用。您调用了 fun2 函数,该函数按原样返回 bal。

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 2020-12-07
      • 2013-01-08
      • 2023-01-26
      相关资源
      最近更新 更多