2
var A = {
   method1 : function(){
      // do some thing
   },

   method2 : function(){
      // do some thing
   }
};

var B = {
  method1 : function(){
   // overriden
  }
};

how to overriden ?

B.extend(B, A);

or

B.merge(A);

What is the right way ?

3 Answers 3

1

One way would be to create a new object that has all the properties of B and inherits from A.

E.g.

function extend(B, A) {
    var Constr = function() {
        for(var prop in B) {
            if(B.hasOwnProperty(prop)) {
                this[prop] = B[prop];
            }
        }
    };
    Constr.prototype = A;
    return new Constr(); 
}

Then you can do:

B = extend({
  method1 : function(){
     // overriden
  }
}, A);

A's methods are unchanged and you don't need an external library ;)

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

Well, you extend the class/object.

I would take a look at the jQuery extend. http://api.jquery.com/jQuery.extend/

That can be used easely to extend your classes/object.

Example:

var A = {
    methode1: function(){
        // Do something
    }
    methode2: function(){
        // Do something else
    }
}

var B = {
    methode1: function() {
        // Do something different then A.methode1
    }
}
var object = $.extend(true, A, B);

1 Comment

Sorry, i come from a java background where you extend classes rather then objects ;). But it's used to extend an 'object' in javascript.
0

In its present form i don't see how B is in any way related to object A [so there's no question of overriding there].

if you really want to have something along the line of inheritance:

var B = A
B.method1 = function() { 
    // overriding
}

so that, invoking B.method2() gets you A's method, while method1() gets overriden by B's version.

2 Comments

thank for suggestion , if follow your way, i always include A, but i don't want . try to imagine what happens if i have 50 function need overriden :( . I want put them in an object
I've had a problem with that however. Making the A.method1 equal to B.methode1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.