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

前端 未结 4 1863
遥遥无期
遥遥无期 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:28

    To add onto the existing answers:

    Making a prototype function would allow changes to it to be inherited. i.e if you write

    function foo(){}
    foo.prototype.bar = function(){return 1};
    function baz(){}
    baz.prototype = new foo();
    new baz().bar(); //returns 1
    foo.prototype.bar = function(){return 2};
    new baz().bar(); //returns 2
    

    However, putting it in the constructor would let other objects inheriting from it also "have" that function, but the function is not inherited.

    function foo(){this.bar = function(){return 1};}
    function baz(){}
    baz.prototype = new foo();
    new baz().bar(); //returns 1
    foo.prototype.bar = function(){return 2};
    new baz().bar(); //returns 1
    

提交回复
热议问题