Execution context in JavaScript

后端 未结 2 1449
一整个雨季
一整个雨季 2021-01-28 12:21

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

相关标签:
2条回答
  • 2021-01-28 12:39

    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.

    0 讨论(0)
  • 2021-01-28 12:46

    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:

    1. in defaul case "this" will be the Window object

      var f = function(){return this;};

      f(); //will return Window object

    2. 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

    3. 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

    4. 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

    5. 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

    0 讨论(0)
提交回复
热议问题