سؤال

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...

هل كانت مفيدة؟

المحلول

I think something like this will solve your problem:

(function() {
  var f = function() {
    //Prototype function
  };
  if(a)
    a.prototype.f = f;
  if(b)
    b.prototype.f = f;
})();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top