user2709155
user2709155

Reputation: 9

How to change this in object?

How to create method twice? I can't understand how to change this in body of function. Why it doesn't work?

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

    for ( var i = 0; i < this.length; i++ ) {
        buf.push(this[i]);
    }
    this = buf;
}

Array.prototype.twice = twice;

a = [1,2,3];
a.twice(); 
a; // [1,2,3,1,2,3]

Upvotes: 0

Views: 56

Answers (2)

user2625787
user2625787

Reputation:

You cannot assign a value to this. That's the rules. But you can modify the value of this. Try pushing some values into this.

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

Array.prototype.twice = twice;

a = [1, 2, 3];
a.twice();
alert(a);

Here's a fiddle. http://jsfiddle.net/Qvarj/ As you can see, most of the logic is yours.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074355

I can't understand how to change this in body of function

If you mean the value of this, you can't. But you don't have to for what you're doing

You're very close, you just have a fair bit to remove:

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

Remember, your array is an object. To change its contents, you just change its contents, you don't have to change the reference to it.

Note, though, that you can use this trick on any modern browser:

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

That works by using the Function#apply function, which calls the function you call it on (so, push in our case) using the first argument you give it as the object to operate on, and the second argument as the arguments to pass into that function (which it takes as an array). More on MDN and in the spec. It happens that push allows you to pass it an arbitrary number of arguments, and will push each one in order. So if you're trying to add the contents of the array to the array a second time, that one line will do it (on modern browsers, some older IE implementations don't like this use of push.apply).

Upvotes: 2

Related Questions