What is the difference between Array.prototype.reverse and Array.reverse in Javascript?

前端 未结 2 1282
故里飘歌
故里飘歌 2021-01-14 06:21

The question I have deals with an application of adding a new method to the existing String constructor. In Object Oriented Program for Javascript by Stoyan

2条回答
  •  情歌与酒
    2021-01-14 07:08

    Is it the case that I have to call upon prototype to access the .reverse() method from the Array object

    No. To access a method on an object, just access it with dot notation. What you want to do is simply

    return this.split('').reverse().join('');
    

    That is just what apply (or call) does:

    var arr = this.split('');
    return arr.reverse.apply(arr).join('');
    

    and finally arr.reverse === Array.prototype.reverse since that's where Array objects do inherit from. You are not accessing the reverse method on the Array constructor function object itself, you are to access the property that all Array instances share - via their prototype. Yet you hardly will ever need to use the prototype object explicitly, that's only when you're dealing with objects that are not Array instances (do not share the prototype) like arguments objects or NodeLists.

    TypeError: missing argument 0 when calling function Array.reverse. That does not make any sense to me.

    Array.reverse is a non-standard Array generic method which is only available in Firefox. It's purpose is to simplify the construct of applying Array prototype methods on other objects, and it does take the array-like object as it's first parameter. An example:

    Array.reverse([0, 1]) // [1, 0]
    

    which is equivalent to

    Array.prototype.reverse.apply([0, 1]);
    

    However, you were doing

    Array.reverse.apply([…]/*, undefined*/)
    

    which is calling the Array.reverse function with the array for the (irrelevant) this value and no actual argument, equivalent to

    Array.prototype.reverse.apply(undefined)
    

    and that throws the rightful exception.

提交回复
热议问题