用Javascript创建简单的构造函数 [英] Creating simple constructor in Javascript

查看:43
本文介绍了用Javascript创建简单的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个构造函数,该构造函数在调用 increment 时会输出以下内容:

I am trying to write a constructor that when increment is called it outputs this:

var increment = new Increment();
alert(increment); // 1
alert(increment); // 2
alert(increment + increment); // 7

我正在尝试这种方式:

var increment = 0;
function Increment(increment){
    increment += 1;
};

但是警报会输出 [object object] .

有什么主意吗?

显然,我不允许触摸现有代码,因为此练习的目的是:«创建一个构造函数,其实例将返回递增的数字»

apparently I am not allowed to touch the existing code, as the cuestion of this exercise is: «Create a constructor whose instances will return the incremented number»

推荐答案

通常,您需要一种增加值的方法,并且需要对其进行调用.

Ususally, you need a method for incrementing the value and you need to call it.

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()); // 7

但是您可以采用构造函数并实现 toString 函数以获取原始值.

But you could take a constructor and implement a toString function for getting a primitive value.

不建议使用此解决方案,但可将其用于教育用途.(在这里它不适用于 console.log ,因为它需要一个期望的环境来获取原始值.)

This solution is not advisable, but it works for educational use. (It does not work with console.log here, because it need an expecting environment for a primitive value.)

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); // 7

这篇关于用Javascript创建简单的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆