javascript:使用多个对象进行原型设计
抱歉,如果在某个地方回答了这个问题(可能是),但我不太确定如何正确询问它,所以我搜索失败了:(
基本上我想做这样的事情:
(a||b).prototype.c = function () {
// do something
}
基本上 a 和 b 是对象。一或者另一个会存在,但不会同时存在,但我不知道哪个会存在,但我需要为其中一个添加一个方法。
现在,我知道我可以这样做:
if (typeof(a) == 'object') {
a.prototype.c = c;
} else if (typeof(b) == 'object') {
b.prototype.c = c;
}
function c () {
// do something
}
但这有 c 的问题。在全球范围内拥有自己的命名空间,我不希望我不希望 c 在任何时候都在全局级别上拥有自己的名称空间。
显然,上面的第一段代码不起作用。或者是这样的?如果之前已经回答过这个问题,请随时关闭并指出正确的方向...
Sorry if this is answered somewhere (it probably is), but I'm not quite sure how to even ask it properly, so I failed at searching :(
Basically I want to do something like this:
(a||b).prototype.c = function () {
// do something
}
Basically a and b are objects. One or the other will exist, but not both. But I don't know which will exist, but I need to add a method to whichever one does.
Now, I know I could do something like this:
if (typeof(a) == 'object') {
a.prototype.c = c;
} else if (typeof(b) == 'object') {
b.prototype.c = c;
}
function c () {
// do something
}
But this has the problem of c having its own namespace on the global level, and I don't want that. I do not want c to have it's own namespace on the global level at any point in time.
Soo...obviously the first bit of code above doesn't work. How would I go about this? Or is something like this simply not possible? Please feel free to close and point me in the right direction if this has been answered before...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这样的事情可以解决你的问题:
I think something like this will solve your problem: