开发者

Using a prototype pattern in a closure

I've been fiddling around a bit with the prototype and closure patterns in Javascript. As you might know, there's a performance penalty when using the closure pattern because it redefines the same functions for every instance of an object. However, the closure pattern does allow for private variables, which makes encapsulation easier.

Here's a typical example of the prototype pattern:

function Foo(val) {
    this.val = val;
}

Foo.prototype.getVal = function() {
    return this.val;
}

var f = new Foo(42);

I was thinking, why can't you do something like this?

function Parent() {

}

Parent.prototype.getVal = function() {
    return this.val;
}

function foo(val) {
    function Ob开发者_C百科j {
        this.val = val;
    }

    Obj.prototype = new Parent();

    return new Obj();
}

var f = foo(42); // Note the missing 'new'

This allows for private variables in the foo() function, and you can even dynamically set the prototype in the foo() function.

I made a jsperf.com test which indeeds shows a big difference in performance, but i don't know why.


The difference in performance is most likely beacuse you are creating two objects instead of one. You are creating one extra object just to use as prototype for the other.

If you want to create a lot of objects like this, you should just create one prototype object and use it as prototype for all objects that you create.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜