Overwrite object functions

  • user warning: Table 'allaboutwebstuff.comments' doesn't exist query: SELECT COUNT(*) FROM comments c WHERE c.nid = 55 AND c.status = 0 in /home/albertoperego/allaboutwebstuff.com/modules/comment/comment.module on line 992.
  • user warning: Table 'allaboutwebstuff.comments' doesn't exist query: SELECT c.cid as cid, c.pid, c.nid, c.subject, c.comment, c.format, c.timestamp, c.name, c.mail, c.homepage, u.uid, u.name AS registered_name, u.signature, u.picture, u.data, c.thread, c.status FROM comments c INNER JOIN users u ON c.uid = u.uid WHERE c.nid = 55 AND c.status = 0 ORDER BY c.thread DESC LIMIT 0, 50 in /home/albertoperego/allaboutwebstuff.com/modules/comment/comment.module on line 992.

Let's say that you have build your class, full of object and variables and it works great, BUT, you need a method of this class to work differently in a certain situation ONLY.
You might know that in object oriented programming you can (and you often have to) use the property called overwriting.
Right, so how does it works in Javascript?

I had today the bad task of debugging someone else code and I've spent hours to figure out what actually was wrong. Here a sample of what I've found:

a = {
    active: function(){
    console.log('day');
    }
};

a.active(); //day

b = a;

b.active = function(){ console.log('night') };

b.active(); //night
a.active(); //night

That's again because b has been associated to the class a doing a=b, which simply gives to b the pointer to a and doesn't create a standalone instance of the class.

I've simply fixed the code using the code as below:

a = {
    active: function(){
    console.log('day');
    }
};

a.active(); //day

temp = a.active;
a.active = function(){ console.log('night') };

a.active();      //night
a.active = temp;
a.active();      //day

I've discussed a similar issue happening with array handling in this post. I hope that this post will save you time when facing the same issue.

Share and Enjoy: