需要扩展 javascript 对象的帮助
假设我有一个 javascript 对象...
app.dooDad = {}
(function (O) {
O.magicStuff = function() {
alert("LOL!");
}
...other methods...
})(app.doodad)
现在假设我对该对象进行了深层复制...
app.specialDooDad = jQuery.extend(true, {}, app.dooDad);
(function (O) {
O.magicStuff = function() {
alert("LOL!");
alert("Cats!");
}
})(app.doodad)
我想知道:是否有更好的方法来做到这一点?也就是说,是否有更好的方法可以使用specialDooDad中的附加命令来扩展magicStuff方法,而无需重写它?
(预先)感谢您的帮助。
Let's say I have a javascript object...
app.dooDad = {}
(function (O) {
O.magicStuff = function() {
alert("LOL!");
}
...other methods...
})(app.doodad)
Now let's say I make a deep copy of this object...
app.specialDooDad = jQuery.extend(true, {}, app.dooDad);
(function (O) {
O.magicStuff = function() {
alert("LOL!");
alert("Cats!");
}
})(app.doodad)
I am wondering: Is there a better way to do this? That is, is there a better way to to extend the method magicStuff with additional commands in specialDooDad, without rewriting it?
thanks (in advance) for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我错了,请纠正我,但我相信你可以在 Javascript 中做这样的事情:
只有当你只是在“原始”函数运行之前或之后添加一两个额外的东西时,这才有效。如果你需要在中间添加东西,我相信你只需要重写这个函数。
我假设您想这样做是为了保持与现有代码库(例如开源库)的向后兼容性?
Correct me if I'm wrong, but I believe you can do something like this in Javascript:
That only works well if you are just adding on an additional thing or two, either before or after the "original" function would run. If you need to add things into the middle, I believe you just have to rewrite the function.
I'm assuming you want to do this to maintain backward compatibility with an existing codebase (such as an open source library)?
我更喜欢这种扩展方式。它更实用。您可以通过组合和扩展来创建新对象。
I prefer this way of extending. It's more functional. You create new objects through composition and extension.