Why defining properties in the prototype is considered an antipattern

后端 未结 6 987
失恋的感觉
失恋的感觉 2021-01-02 18:59

I often see this pattern to define javascript objects

function Person(name) {
    this.name = name;
}
Person.prototype.describe = function () {
    return \"         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 19:15

    There's nothing wrong with that code. This is supposedly what is meant:

    function Person(name) {
        this.name = name;
    }
    Person.prototype.age = 15; //<= adding a hardcoded property to the prototype
    

    Now you will see this:

    var pete = new Person('Pete'), mary = new Person('Mary');
    pete.age; //=> 15
    mary.age  //=> 15
    

    And most of the time, that's not what you want. Properties assigned to the prototype of a constructor are shared between all instances, properties assigned within the constructor (this.name) are specific for the instance.

提交回复
热议问题