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 Obj {
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.
链接地址: http://www.djcxy.com/p/60774.html上一篇: 是关于JavaScript的原型封闭好的做法方面的一件好事
下一篇: 在闭包中使用原型模式