Setting javascript prototype function within object class declaration

前端 未结 5 647
既然无缘
既然无缘 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:24

    That is because privateVar is not a private member of the object, but part of stamp's closure. You could get the effect by always creating the function:

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

    The value of privateVar is set when the function is built, so you need to create it each time.

    EDIT: modified not to set the prototype.

提交回复
热议问题