Does this have a link to easily identify a good or bad idea?

I sometimes assign this pointer to var. The advantage of this is that I do not lose the possibility of anonymous callback functions. Is this a good or bad idea?

Example:

var Foo = (function($) {
  var Foo = function() {
    var self;

    self = this;

    this.init = function() {
      $('#foo').click(function(e) {
        self.onClick();
      });
    };

    this.onClick = function() {
      console.log(this);
    };

    this.init();
  };

  return function() {
    return new Foo();
  };
})(jQuery);

Thank!
{Jim}

+3
source share
5 answers

If you need a reference to the value of the thiscontained area (which, of course, is a reasonable requirement), this should be a good idea, especially in cases where you do not control the function call (for example, the event handler function), where this is your only option.

+3
source

, . /.


, :

A this - , execution context. , (, ).

  • this .
  • this . this , .

, . , , , this value .

+1

. , .

- onClick . this onClick . :

var Foo = (function($) {
  var Foo = function() {
    this.init = function() {
      $('#foo').click(function(e) {
        onClick();
      });
    };

    var self = this;  // Or use ES5 Function.prototype.bind

    var onClick = this.onClick = function() {
      console.log(self);
    };

    this.init();
  };

  return function() {
    return new Foo();
  };
})(jQuery);

self ( that , ), ( ).

+1

, , , "this" "self", . "this" Function.prototype.bind, ECMAScript 5 . , Google Chrome, , , polyfill, .

+1

, . ( ):

var self;
self = this;

:

var self = this;
0
source

Source: https://habr.com/ru/post/1787910/


All Articles