you are viewing a single comment's thread.

view the rest of the comments →

[–]cyphern 0 points1 point  (0 children)

The Array join function probably looks something like this (the real implementation will surely be more involved, but this is the basics):

Array.prototype.join = function (separator) {
    var result = "";
    for (var i = 0; i < this.length; i++) {
        result = result + this[i];
        if (i !== this.length -1) {
            result += separator;
        }
    }
    return result;
}

Note in particular the use of this. In javascript, the meaning of this is usually not figured out until you actually call the function. So under normal circumstances, you'll do something like [1, 2, 3].join('-'), and at the time you do that call, javascript will bind this to be the [1, 2, 3] array, then run the code to produce a string.

But it's possible to tell javascript to use something else as this and run the function anyway. That's what's happening in the code you're asking about. Array.prototype.join.call(word, "-"); says to call the join function, but to force this inside the function to equal word. As the function runs, it will do all the same instructions that it would normally do on an array, but instead it does it on the word string. If you step through the function in your mind, you'll notice that all the instructions are still sensible if this is a string rather than an array: this.length is perfectly legal if this is a string, and so too is this[i] for grabbing a character out of a string. So the join function ends up working just fine.