javascript - How to change this in object? -


how create method twice? can't understand how change in body of function. why doesn't work?

function twice() {     var buf = [];     ( var = 0; < this.length; i++ ) {         buf.push(this[i]);     }      ( var = 0; < this.length; i++ ) {         buf.push(this[i]);     }     = buf; }  array.prototype.twice = twice;  = [1,2,3]; a.twice();  a; // [1,2,3,1,2,3] 

i can't understand how change in body of function

if mean value of this, can't. don't have you're doing

you're close, have fair bit remove:

function twice() {     var i, l;     (l = this.length, = 0; < l; ++i) {         this.push(this[i]);     } } 

remember, array object. change contents, change contents, don't have change reference it.

note, though, can use trick on modern browser:

function twice() {     this.push.apply(this, this); } 

that works using function#apply function, calls function call on (so, push in our case) using first argument give object operate on, , second argument arguments pass function (which takes array). more on mdn , in spec. happens push allows pass arbitrary number of arguments, , push each 1 in order. if you're trying add contents of array array second time, 1 line (on modern browsers, older ie implementations don't use of push.apply).