简体   繁体   中英

Javascript Invalid left-hand side in assignment

In an attempt to add queue type functionality to nodejs's Buffer class, I have constructed the following function:

Buffer.prototype.popleft = function(n) {
  tRet = this.slice(0,n);
  this = this.slice(n,this.length-1); // error here
  return tRet;
};

however, this code yields the following error: "ReferenceError: Invalid left-hand side in assignment"

I know that the issue is with the assignment of 'this' within the function, what I dont know is better way of accomplishing this same type of logic.

EDIT:

Ended up writing an object around the Buffer as shown below:

sPort.vBuffer = {}
sPort.vBuffer.buff = new Buffer(0);
sPort.vBuffer.off = 0;
sPort.vBuffer.expect = -1;

sPort.vBuffer.ReadChr = function() {
    this.off ++;
    return this.buff[this.off - 1];
};

sPort.vBuffer.ReadUInt32LE = function() {
    this.off += 4;
    return this.buff.readUInt32LE(this.off - 4);
}

sPort.vBuffer.ReadInt32LE = function() {
    this.off += 4;
    return this.buff.readInt32LE(this.off - 4);
}

sPort.vBuffer.Write = function(aData) {
    this.buff = Buffer.concat([this.buff.slice(this.off),aData])
    this.off = 0;
};

You can't assign to this . You can assign to a copy of it, but in your case it looks like that won't do any good.

According to the Node documentation, Buffer instances cannot be resized. Now, whether that's because Node simply provides no APIs to do that, or because of some set of internal implementation assumptions/dependencies, I don't know. There sure doesn't look like any way to alter the length of a Buffer instance.

You could use .copy to shift the contents, and then fill the last position(s) with some dummy value ( null or undefined I guess).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM