How to solve this kind of JS code problem?

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;

Dec.01,2021

var Sequence = function(){}
Sequence.current = 0;
Sequence.prototype.next = function(){return PPSequence.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());

A single case is fine

example:
https://codepen.io/LiangWei88.

Code:

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

see .Next () , I feel that I should be taking the ES6 Generator exam. I grabbed a link Generator implementation you can take a look. Or go to MDN's

the above answer is good, but to prevent accidental changes to the value of count , you can use closures to make it private. You are not sure whether you expect sequence1 and sequence2 to be the same instance here. If so, you can use singleton mode.

is roughly as follows:

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 PPcount
    }

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

in addition, in es6, you can also use generator to do this, specifically without posting the code.


read it wrong, the one upstairs is good, and it's better to use singleton mode. Here, everyone gets the same reference, which saves memory.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e496e3-43cab.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e496e3-43cab.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?