How to call an external "this" in an internal function?

I defined two functions for the array:

Array.prototype.remove = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            this.removeAt(i);
        }
    }
};
Array.prototype.removeAll = function(array2) {
    array2.forEach(function(item) {
        this.remove(item);  // remove not found!!
    });
}

But in function, removeAllhe reports function remove is not found. I will fix it like this:

Array.prototype.removeAll = function(array2) {
    var outer = this;
    array2.forEach(function(item) {
        outer.remove(item);  
    });
}

But it is ugly. Is there a better way?

+5
source share
4 answers

Transmission thisusing another variable, as well as an idiomatic approach. There is nothing ugly about this. (Most often the variable is called thator self)

+6
source

Passing the next one forEach argument , which will have a context thisin the callback function, in your case thisrefers to the window object.

Array.prototype.removeAll = function(array2) {

    array2.forEach(function(item) {
        this.remove(item);  
    },this);
}
+2
source

bind ( Function.prototype), this , :

Array.prototype.removeAll = function(array2) {
    array2.forEach(function(outer){
     return function(item) {
        outer.remove(item);  
    };}(this));
}

curry

function curry() {
  var fn = Array.prototype.shift.call(arguments), 
      args = Array.prototype.slice.call(arguments);
  return function curryed() {
    return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
  };
};



Array.prototype.removeAll = function(array2) {
    array2.forEach(curry(function(item) {
        outer.remove(item);  
    },this));
}

Function.prototype, bind, , MDN : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

+2

Function.bind ..

array2.forEach((function(item) {
    this.remove(item);  
}).bind(this));

, , " " / ( ), .

var self = this...

.

+1

All Articles