Javascript - override method

var A = { method1 : function(){ // do some thing }, method2 : function(){ // do some thing } }; var B = { method1 : function(){ // overriden } }; 

how to override?

 B.extend(B, A); 

or

 B.merge(A); 

What is the right way?

+2
javascript
source share
3 answers

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

eg.

 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 methods do not change and you do not need an external library;)

Demo

+1
source share

Well, you extend the class / object.

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

This can be easily used to extend your classes / objects.

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
source share

In its current form, I do not see how B is connected in any way with object A [so there are no questions about redefinition there].

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

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

so when you call B.method2() you get A's method, and method1() will get a higher version of B's .

0
source share

All Articles