I have an object named Gallery with several properties and methods. One of them, setCurrentPicture, removes all existing photos and videos DOM elements from gallery container b
I should add bind this to Array.prototype.forEach.call instead of implementing this to callback function.
Array.prototype.forEach.call(container.children, function(item) {
if (item.tagName === 'VIDEO') {
document.removeEventListener('click', this.togglePlayVideo);
}
if (item.tagName === 'VIDEO' || item.tagName === 'IMG') {
container.removeChild(item);
}
}.bind(this));
Thanks to all for the answers.
The best for you is to get familiar with what is "this" and what is "bind". You can do this by reading this brilliant description
and second part
To cut a long story short - when you declare a function with "this" like this:
in defaul case "this" will be the Window object
var f = function(){return this;};
f(); //will return Window object
when an object owns a link to your function like this:
var f = function(){return this;};
var o = {func: f};
o.func(); // will return the "o" object becuase "this" becomes o object
when you use explicit binding like call/apply you'll set this to a particular value like this:
var f = function(){return this;};
var obj = {};
f.call(obj); // will return your obj
and there is so called "hard binding". used like this:
var f = function(){return this;};
var obj1 = {num:1};
var obj2 = {num:2};
var boundFunc = f.bind(obj1); //now it's hardbound to obj1
//let's try to switch this by using "call"
boundFunc.call(obj2); // will return obj1, because it's hardbound
and this can be affected when function is called with "new" keyword:
f = function(){ this.a =1; this.b =2; };
var obj = new f(); // will set brand new object as "this" and return it
//so we will get {a:1, b:2} object as a result