我正在尝试编写一个构造函数,该构造函数在increment被调用时会输出以下内容:
var increment = new Increment();
alert(increment); // 1
alert(increment); // 2
alert(increment + increment); // 7
Run Code Online (Sandbox Code Playgroud)
我正在尝试这样:
var increment = 0;
function Increment(increment){
increment += 1;
};
Run Code Online (Sandbox Code Playgroud)
但是警报输出[object object]。
任何的想法?
编辑:显然,我不允许触摸现有代码,因为此练习的提示是:«创建一个构造函数,其实例将返回递增的数字»
通常,您需要一种增加值的方法,并且需要对其进行调用。
function Increment(value) {
this.value = value || 0;
this.inc = function () { return ++this.value; };
}
var incrementor = new Increment;
console.log(incrementor.inc()); // 1
console.log(incrementor.inc()); // 2
console.log(incrementor.inc() + incrementor.inc()); // 7Run Code Online (Sandbox Code Playgroud)
但是您可以采用构造函数并实现一个toString用于获取原始值的函数。
不建议使用此解决方案,但可将其用于教育用途。(它console.log在这里不起作用,因为它需要一个期望的环境来获取原始值。)
function Increment(value) {
value = value || 0;
this.toString = function () { return ++value; };
}
var increment = new Increment;
alert(increment); // 1
alert(increment); // 2
console.log(increment + increment); // 7Run Code Online (Sandbox Code Playgroud)