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

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

    I think I'm answering the right question here, otherwise let me know.

    The difference is that using prototype results in only 1 instance.

    So, for example, baz.bar in one instance is the same as baz.bar in another. They will share values within the 'foo' instance:

    function foo() {
        var x = 0;
        this.bar = function() {};
    
        this.getVal = function() {
            return x;
        }
    
        this.setVal = function(val) {
            x = val;
        }
    }
    
    function baz() {}
    
    baz.prototype = new foo();
    
    var a = new baz(),
        b = new baz();
    
    a.setVal("1234")
    console.log(b.getVal()); // prints '1234'
    

    http://jsfiddle.net/jonathon/7GtRD/

    If a and b were directly calling 'foo', then they wouldn't be sharing the values within the foo. However, this is where it differs slightly between setting this.bar and using the prototype to create bar.

    Using the prototype would create one instance of bar. So a.bar will be the same as b.bar. If you do it the other way, they will be two different functions (doing the same thing).

提交回复
热议问题