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

后端 未结 4 1421
既然无缘
既然无缘 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: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.

提交回复
热议问题