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

前端 未结 2 1256
故里飘歌
故里飘歌 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 06:57

    Array.reverse is undefined (at least in Chrome 29) - Array.prototype.reverse is a function that will reverse the order of the "iterable" it is called on.

    The key thing to note here is that Array is not a class like you would have in Java - rather it is a constructor:

    [].constructor === Array;
    // true
    

    The prototype property of Array is actually what is providing the behavior to any particular instance of Array:

    Object.getPrototypeOf([]) === Array.prototype;
    // true
    
    // Bad idea, just for an example
    var guys = ['Tom', 'Harry', 'Richard'];
    Array.prototype.exclaim = function() {
        return this.join(", ") + "?!?!?!";
    }; 
    guys.exclaim();
    // Tom, Harry, Richard?!?!?!
    

    The key here is that JavaScript uses a prototype-based object-oriented pattern, rather than the classical pattern you are more likely familiar with. Instead of having "classes" which contain all the behaviors, but which are distinct from instances, JavaScript has objects, which can be the "prototypes" of other objects, providing data and behavior to the child objects.

    // Totally licit OO pattern in JavaScript
    var prototypeClass = {
        method1: function() { console.log("Hello from method 1!"); },
        method2: function() { console.log("Hello from method 2!"); },
        classData: 42 
    };
    
    var prototypeInstance = Object.create(prototypeClass);
    
    prototypeInstance.method1()  // Hello from method 1!
    prototypeInstance.classData  // 42
    
    // And you can modify the class after
    // instantiating instances and the changes
    // will be picked up by the instances
    prototypeClass.happyPrimes = "Don't they teach recreational mathematics anymore?";
    
    prototypeInstance.happyPrimes // The quote from 42
    

提交回复
热议问题