Is there any difference between constructor function and prototype object when using inheritance?

前端 未结 4 1892
遥遥无期
遥遥无期 2021-01-13 00:10

Consider the following to JavaScript snippets:

function foo() {
  this.bar = function() { };
}

// or... (if we used an empty constructor function)

foo.prot         


        
4条回答
  •  难免孤独
    2021-01-13 00:35

    One big difference is that if you change properties of the prototype those changes will apply to all instances, including those that already exist, whereas if you change a property that was created in the constructor it will only change it for the instance you change it on.

    Regarding what some of the other answers said about setting bar in the constructor resulting in each instance having its own copy of the function: that's true if you have a function expression inside the constructor as shown in the code in the question, but not true if you assign a function reference like this:

    function myFunction() {}
    
    function foo() {
       this.bar = myFunction;
    }
    

    In that case all instances will have a bar property that refers to the same function - but an individual instance could still have its bar property assigned to something else without affecting other instances.

提交回复
热议问题