How do I override an object method in JavaScript?

Why was JavaScript designed such that "this" refers to the object invoking a function, rather than the object containing the function invoked?

  • In other programming languages the "this" keyword, or its equivalent, typically refers to the object in which a method is defined.  In Javascript "this" can change depending on what calls a function and whether or not you invoke a function using method syntax.  It often requires workarounds to get the typical behavior you'd expect.  I assume this was a deliberate design decision, but was wondering why it was made, and if it has any benefits. More information (but not an answer as to why) available here: http://stackoverflow.com/questions/80084/in-javascript-why-is-the-this-operator-inconsistent

  • Answer:

    I think Alan Storm's reply on SO answers the question, albeit at length. It's useful when you want to use a generic function for multiple objects: var s, c, o1, o2; s = function (newStatus) { this.status = newStatus.toUpperCase() || "NONE"; return this; // allow method chaining, ala jQuery }; c = function () { console.log(this.status); return this; }; o1 = { status: "", setStatus: s, log: c }; o2 = { status: "", update: s writeStatus: c }; o1.setStatus("object 1").log(); // "OBJECT 1" o2.update("hello, world!").writeStatus(); // "HELLO, WORLD!" // Even works on anonymous objects: ({ status: "INIT", say: c }).say(); // "INIT" Regarding the "requires workarounds to get the typical behavior you'd expect", this is only true if you expect it to work like a classical language. JavaScript is not a classical language so getting out of that mindset will make things easier on you :-)

Andy Farrell at Quora Visit the source

Was this solution helpful to you?

Other answers

I wager the reason why is that the functions can be passed around. In most OO languages, the binding of "this" to the object is very much a part of the class structure. Whereas in JavaScript, there is no tight binding between objects and functions.

Jeffrey M. Barber

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.