0

I have seen come code which is related to addEventListener function and this keyword in JavaScript.

I know this refers to the global object and addEventListener registers the specified listener on the EventTarget it's called on.

var Something = function (element) {
  this.name = 'Something Good';
  this.onclick1 = function (event) {
    console.log(this.name);
  };
  this.onclick2 = function (event) {
    console.log(this.name);
  };
  element.addEventListener('click', this.onclick1, false);
  element.addEventListener('click', this.onclick2.bind(this), false);
}

Here I just need to know how the last line of this above script works:

element.addEventListener('click', this.onclick2.bind(this), false); 

I understand what bind does -- I just need to know what do the two thiss represents in this.onclick2.bind(this). Do they represents element and event attributes, that is, is it acting like element.onclick2.bind(event)?

Karim AG
  • 2,166
  • 15
  • 29
  • By creating a simple test case you'll find out. – Teemu Apr 10 '14 at 08:58
  • I am not sure for the answer for addEventListener, in setTimeout case, I know the answer. And I'm pretty sure it is the same. So, what is happening ? You give some argument to a method of element. So "this" represents "element", and not the instance of "Something". – vekah Apr 10 '14 at 09:00
  • http://stackoverflow.com/questions/17241781/is-it-better-to-bind-this-or-use-a-variable/17242228#17242228 – Jean-Paul Apr 10 '14 at 09:00
  • @vekah so this represents the element variable right here ?. – user3517846 Apr 10 '14 at 09:03
  • Yes, I am pretty sure. You should still try some tests on it. For instance, if you were calling window.setTimeout instead of addEventListener, "this" would represent "window" and not the instance of your class "Something". – vekah Apr 10 '14 at 09:05

1 Answers1

0
this.onclick2.bind(this)

This piece of code returns the onclick2 function with its this variable bound to the argument passed to .bind(), which is this, in this case.

For example:

function testing(parameter){
    console.log(parameter, this);
}
var boundFunction = this.testing.bind({ someKey: 'SomeValue'});
boundFunction("Testing 1 2 3");

Will log:

"Testing 1 2 3", {someKey: "SomeValue"}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147