JZ.
JZ.

Reputation: 21877

How do you extend an Object in javascript

I have the following object:

Test.Beta.MyObject = function($) {

  var foo = {};

  foo.blah = function(attribute, validation) {
    if (attribute === "yey") {
      return false;
    }
      return true;
    };

  return foo;
}(jQuery);

How do I keep the above file in place, and extend the object somewhere else? How do I insert this new method of foo in another file....

foo.bar = function(attribute, validation) {
        if (attribute === "moo") {
          return false;
        }
          return true;
        };

Upvotes: 1

Views: 94

Answers (2)

Ibu
Ibu

Reputation: 43810

Test.Beta.MyObject = function($) {
  // old code
  .....
  foo.extend = function (fn) {
     foo.prototype = fn;
  }

  return foo;
}(jQuery);

Upvotes: 1

scottm
scottm

Reputation: 28701

Adding it to the prototype of your object is going to be the best bet if you intend to be able to call it for every instance of MyObject:

Test.Beta.MyObject.prototype.bar = function(attribute, validation) {
        if (attribute === "moo") {
          return false;
        }
          return true;
        };

Upvotes: 2

Related Questions