JavaScript help with 'this'

JavaScript help with 'this'


I have problem with access to some elements of my object within its methods. I need to have access to some object parameters in my function with is used in addEventListener method. I use .bind(this) but becouse of that i lose information about element that triggered event and I need them too. How cen I have acces to both object paramiters and triggering element ?

Some cod:

  var myObjest= {
     someVar: 5,
     someHtmlElement: document.getElementsByClassName("Div")[0],
     someMetod: function() {
         console.log("someVar= "+someVar+"triggered by "+ this);
     bind: function(){

How cen I acces ‘someVar’ within ‘someMetod’


I don’t think you can do it, as the function i s out of your sight over their. Try avoiding this kind of complicating, especially when using JS as it can lead to a lot of errors that can be hard to detect later. If you think you need some help with it you can always try to use a program to help you. I use checkmarx these days and it works pretty good… Just make sure you try to avoid those errors as much as you can.
Good luck!


Pretty sure there are built-in methods that already do what your function is trying to do.

But if you want to override the ‘this’ of a function, use .call.

You don’t actually have to use ‘this’ though. You can access any global object’s variable by calling the object first.

So you could do

console.log("somevar=" + myObjest.someVar + " triggered by " + this);

Or for more flexibility pass the whole object as a parameter

  someMetod: function(object1, object2) {
    console.log("someVar= " + object1.someVar + " triggered by " +;

myObjest.someMetod(myObjest, {name:"Bob"});


I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.