Difference between Array.slice and Array().slice

后端 未结 6 1105
醉酒成梦
醉酒成梦 2020-12-12 21:04

I am going through John Resig\'s excellent Advanced javascript tutorial and I do not thoroughly understand what\'s the difference between the following calls: (please note t

6条回答
  •  星月不相逢
    2020-12-12 21:37

    Not quite.

    Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2):

    >>> String.substring.call("foo", 1)
    "1"
    
    >>> String().substring.call("foo", 1)
    "oo"
    

    Array.slice is neither properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).

    The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. Try running the equivalent code in IE and you'll get an error that Array.slice is null.

    This is why Array.slice does not behave correctly (nor does String.substring).

    Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):

    >>> Array.slice.call([1,2], [3,4])
    3,4
    

    Now, if you properly call slice() on either an instantiated object or the Array prototype, you'll get what you expect:

    >>> Array.prototype.slice.call([4,5], 1)
    [5]
    >>> Array().slice.call([4,5], 1)
    [5]
    

    More proof...

    >>> Array.prototype.slice == Array().slice
    true
    >>> Array.slice == Array().slice
    false
    

提交回复
热议问题