在javascript对象中使用闭包作为构造函数的最佳实践

时间:2014-11-14 23:00:22

标签: javascript constructor closures

这是关于最佳做法的一般性问题。我知道javascript是一种原型语言,并没有传统意义上的构造函数,但使用闭包来创建一个类似于更基于类的语言的构造函数是否有任何问题?我的意思是这样的:

var foo = function () {
    this.bar = undefined; //this.bar is a field not a method
    (function (that) {

        //lots of processing needs to happen to determine what 
        //the value of bar should be

    })(this); // passing in this give us access to this.bar
}

foo.prototype.getbar = function () {
    return this.bar
}

我发现这在将html2canvas库转换为angularjs服务时非常有用,但是想知道这是不是很糟糕的做法。

0 个答案:

没有答案