Setting javascript prototype function within object class declaration

前端 未结 5 638
既然无缘
既然无缘 2020-12-04 20:08

Normally, I\'ve seen prototype functions declared outside the class definition, like this:

function Container(param) {
    this.member = param;
}
Container.p         


        
5条回答
  •  借酒劲吻你
    2020-12-04 20:25

    To get the behavior you want you need to assign each individual object separate stamp() functions with unique closures:

    Container = function(param) {
        this.member = param;
        var privateVar = param;
        this.stamp = function(string) {
            return privateVar + this.member + string;
        }
    }
    

    When you create a single function on the prototype each object uses the same function, with the function closing over the very first Container's privateVar.

    By assigning this.stamp = ... each time the constructor is called each object will get its own stamp() function. This is necessary since each stamp() needs to close over a different privateVar variable.

提交回复
热议问题