这种JS代码题,要如何解?

新手上路,请多包涵

please create a tool to generate Sequence
Expected to be used like:
var sequence1 = new Sequence();
sequence1.next() --> return 1;
sequence1.next() --> return 2;

in another module:
var sequence2 = new Sequence();
sequence2.next() --> 3;
sequence2.next() --> 4;

阅读 3k
5 个回答
var Sequence = function(){}
Sequence.current = 0;
Sequence.prototype.next = function(){return ++Sequence.current;}

var sequence1 = new Sequence();
console.log(sequence1.next());
console.log(sequence1.next());

var sequence2 = new Sequence();
console.log(sequence2.next());
console.log(sequence2.next());

单例就好

例子:
https://codepen.io/LiangWei88...

代码:

Sequence = function() {
  var instance = this;
  this.count = this.count || 0
  this.next = () => {
    this.count +=1;
    console.log(this.count);
  }
  Sequence = function() {
    return instance;
  }
}

var sequence1 = new Sequence();
sequence1.next();
sequence1.next();

var sequence2 = new Sequence();
sequence2.next();
sequence2.next();

上面的答案已经不错了,不过防止意外更改 count 的值,可以借闭包将它变为私有,不确定你这里是否期望 sequence1 和 sequence2 为同一个实例,如果是的话,则可以使用单例模式。

大体如下:

var Sequence = (function(){
    var instance;
    var count = 0
    var _Sequence = function () {
        if(instance) {
            return instance;
        }

        // instance = this;
        // return instance;
        return instance = this;
    }
    
    _Sequence.prototype.next = function() {
        return ++count
    }

    return _Sequence;
})()

var sequence1 = new Sequence();
console.log(sequence1.next()) 
console.log(sequence1.next())


// in another module:
var sequence2 = new Sequence();
console.log(sequence2.next())
console.log(sequence2.next())

另外,在 es6 中,还可以使用 generator 来做,具体就不贴代码了。

额看错了,楼上的写的不错,用单例模式更好这边,所有人拿到的都是同一个引用,这样可以节省内存。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题