

X again, we used ‘he’ which is referring to Mr. To understand ‘this’ better in a practical way, we can consider an example Mr. As by the word (this) itself, we can understand that it’s referring to something. Basically, ‘this’ keyword is used to refer to some object or function in JavaScript.

The solution above will assing this to that then we can and access the name property inside the sayHi method from that, so this can be called without issues inside the DOM call.Īnother solution is to assign an empty that object and add properties and methods to it and then return it.

Var element = document.getElementById('button') Įlement.addEventListener('click', ahmad.sayHi) // => Ahmad Sometimes this can refer to another scope and refer to something else, for example suppose you want to call a constructor method inside a DOM event, in this case this will refer to the DOM element not the created object. Like El Ronnoco hints at Douglas Crockford thinks this is a good idea. It's an easily recognizable convention for overcoming a shortcoming in the language. This is why the very general sounding name that is used. This is a pain.Ĭreating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). you could also use car.starter, but using 'that' gives 'this.starter' is undefined, so we use 'that' instead. you can access car.starter inside this method with 'this' I'm going to begin this answer with an illustration: var colours = ĭocument.getElementById('element').addEventListener('click', function()
