如何使用 ES5 Object.create 和对象字面量语法模拟构造函数?
假设我有一个像这样的对象:
var Foo = {
x: 5,
sprite: new Image()
}
问题:我想用正确的 src 初始化该精灵。但是,当我使用以下创建技术时:
var f = Object.create(Foo);
我没有构造函数方法(也称为 init 函数)来设置 sprite.src = 'cool.png';
我的问题:
如果我使用对象文字技术和 Object.create()
,我什么时候真正初始化一些内部状态(例如 new Image()
的示例)
我的解决方案:
var Foo = {
create: function() {
var f = Object.create(Foo);
f.sprite.src = 'cool.png';
return f;
}
}
但是,我不知道这是否是一个很好的模式。如果有办法的话,我想用“JavaScript Way”来做到这一点。 :)
谢谢!
Presume I have an object like this:
var Foo = {
x: 5,
sprite: new Image()
}
Problem: I want to initialize that sprite with the right src. However, when I use the following creation technique:
var f = Object.create(Foo);
I don't have a constructor method (aka init function) to setup sprite.src = 'cool.png';
My question:
If I am using the object literal technique, and Object.create()
, when do I actually initialize some of my internal state (like the example of the new Image()
)
My solution:
var Foo = {
create: function() {
var f = Object.create(Foo);
f.sprite.src = 'cool.png';
return f;
}
}
However, I don't know if that's a great pattern. I'd like to do this the "JavaScript Way" if there is a way. :)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我所做的事情与您上面写的非常相似,但我将其与模块模式结合起来:
从外部,这公开了
Vehicle.create()
和Vehicle.prototype
。然后,如果我想创建派生类型,我可以这样做:这种模式让我可以派生类型,而不会出现
Car.prototype = new Vehicle()
的错误,即失败 如果我的构造函数带有参数。I do something very similar to what you've written above, but I combine it with the module pattern:
From the outside, this exposes
Vehicle.create()
andVehicle.prototype
. Then if I want to make a Derived type, I can do this:This pattern lets me derive types without making the error of
Car.prototype = new Vehicle()
, which is fail if my constructors take parameters.正如我可以从这个 链接 假设的那样,您应该执行以下操作:
As I can assume from this link you should do something like:
我认为这篇文章总结得很好:
http://www.bennadel.com/blog/2184-Object-create-Improves-Constructor-Based-Inheritance-In-Javascript-It-Doesn-t-Replace -It.htm
I think this article sums it up pretty nicely:
http://www.bennadel.com/blog/2184-Object-create-Improves-Constructor-Based-Inheritance-In-Javascript-It-Doesn-t-Replace-It.htm
我会简单地这样做:
I would simply do this:
长话短说:不要尝试。 Object.create 的基本思想是避免构造函数。您最好使用这个好的旧模式:
然后使用
new Foo
而不是Object.create
。To cut a long story short: Don't try. The basic idea of Object.create is avoiding constructor functions. You're better off using this good old pattern:
Then use
new Foo
instead ofObject.create
.