在闭包中使用原型模式
我一直在摆弄 Javascript 中的原型和闭包模式。您可能知道,使用闭包模式时会性能损失,因为它重新定义了相同的函数对象的每个实例。然而,闭包模式确实允许私有变量,这使得封装更容易。
这是原型模式的一个典型示例:
function Foo(val) {
this.val = val;
}
Foo.prototype.getVal = function() {
return this.val;
}
var f = new Foo(42);
我在想,为什么不能做这样的事情呢?
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'
这允许在 foo() 函数中使用私有变量,甚至可以在 foo() 函数中动态设置原型。
我做了一个 jsperf.com 测试,它确实显示了性能上的巨大差异,但我不知道为什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
性能差异很可能是因为您创建的是两个对象而不是一个。您正在创建一个额外的对象,只是为了用作另一个对象的原型。
如果您想创建很多这样的对象,您应该只创建一个原型对象并将其用作您创建的所有对象的原型。
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.