看起来您希望Sum 成为一个构造函数。您不是直接通过new 调用构造函数。所以:
var s1 = new Sum();
var s2 = new Sum();
在s1 和s2 中没有new 的原因是Sum 不会在任何地方执行return x,因此调用它的结果是值undefined。但是当你使用new 时,new 表达式的结果就是创建的对象。
FWIW,Sum 还有另一个问题:您在几个地方遗漏了this.(还有几个分号,尽管自动分号插入会为您添加它们):
function Sum() {
this.result = 0;
this.getCurrentSum = function getCurrentSum() {
return this.result;
// −−−−−−−−^^^^^
};
this.add = function add(add_number) {
this.result += add_number;
// −^^^^^
};
}
JavaScript 不像 Java 或 C#,this. 不是可选的。
在您提出的评论中:
如果我可以更改 Sum 函数或函数内部的任何内容,但我无法更改 var s1 = Sum();calling?
在这种情况下,您可以将 Sum 设为 builder 函数并让它返回一个对象,如下所示:
function Sum() {
return {
result: 0,
getCurrentSum: function getCurrentSum() {
return this.result;
},
add: function add(add_number) {
this.result += add_number;
}
};
}
现场示例:
(function () {
function Sum() {
return {
result: 0,
getCurrentSum: function getCurrentSum() {
return this.result;
},
add: function add(add_number) {
this.result += add_number;
}
};
}
var s1 = Sum(); // here s1 is undefined
var s2 = Sum(); // here s2 is undefined
s1.add(10); // here cannot execute add of undefined crash
s1.add(20);
s2.add(30);
s2.add(5);
// must print 30
console.log(s1.getCurrentSum());
// must print 35
console.log(s2.getCurrentSum());
})();
通常,构建器函数不会以大写字母开头(本质上是为构造函数保留的),因此它的名称应类似于 createSum 或 buildSum 或类似名称。
Sum 的那个版本是用 ES5 级别的语法编写的(实际上它甚至是 ES3 级别的)。在 ES2015+ 中可能会更简洁一些:
// ES2015+ using method syntax
function Sum() {
return {
result: 0,
getCurrentSum() {
return this.result;
},
add(add_number) {
this.result += add_number;
}
};
}
现场示例:
(function () {
// ES2015+ using method syntax
function Sum() {
return {
result: 0,
getCurrentSum() {
return this.result;
},
add(add_number) {
this.result += add_number;
}
};
}
var s1 = Sum(); // here s1 is undefined
var s2 = Sum(); // here s2 is undefined
s1.add(10); // here cannot execute add of undefined crash
s1.add(20);
s2.add(30);
s2.add(5);
// must print 30
console.log(s1.getCurrentSum());
// must print 35
console.log(s2.getCurrentSum());
})();