What's the difference between this.bla to Object.prototype.bla

后端 未结 4 1362
既然无缘
既然无缘 2021-01-20 11:30

Let\'s say I have this code:

(function(global) {
    function Bar(foo) {
        this.foo = foo;
        return this;
    }

    Bar.prototype.getFoo = funct         


        
相关标签:
4条回答
  • 2021-01-20 12:14

    The quick answer = function sharing + smaller memory footprint

    When you're using prototype.functionName all instances share the same function (only one copy in memory), but if you use this.functionName in your constructor each instance has its own copy of the same function (exists multiple times in memory).

    Using prototype has two implications:

    1. Memory footprint - as mentioned
    2. Subsequent function change on the prototype is reflected on all existing (and future of course) instances - there are rare occasions when one would like to do this, but it's there any it can be used

    Advanced - you can have both

    You can also have both in which case the local copy has precedence over the prototype which means that you could do stuff like this:

    function Crazy(name)
    {
        this.name = name;
        this.callMe = function() {
            return "Where are you " + this.name;
        };
    }
    
    Crazy.prototype.callMe = function() {
        return this.name + " come here";
    };
    
    var inst = new Crazy("Robert");
    inst.callMe(); // "Where are you Robert"
    delete inst.callMe;
    inst.callMe(); // "Robert come here"
    
    0 讨论(0)
  • 2021-01-20 12:17

    An aside :

    With prototypal inheritance, there's a fundamentel difference between own properties and inherited ones.

    Sometimes this can be quite relevant.

    A classic for loop that is often used, only checks for the 'own properties', taking this form :

    for (prop in array) {
    if (array.hasOwnProperty(prop)) {
          dostuff
    }
    

    When assigning to this, alle properties are own properties, making the hasOwnProperty check irrelevant.

    0 讨论(0)
  • 2021-01-20 12:21

    When you use prototype, the function is shared, when you assign the function to this, they are not. Instead, every instance will have its own copy of the funciton.

    0 讨论(0)
  • 2021-01-20 12:32

    If you have more than one instance of the "class" (using the term loosely), they all share the same prototype. So attaching things there is more light-weight, and it guarantees that they all have the same version (if that is what you want).

    Think about it as instance fields vs class fields.

    Prototypes can also be chained to allow for "inheritance" of fields.

    0 讨论(0)
提交回复
热议问题