this
is one of the more painful aspects of JavaScript. What it refers to will depend on how and where the function is called.
If you just call
FollowEl(x, s)
, then
this
will be the global object. In a browser, that would be the
window
object.
NB: This happens regardless of whatever
this
refers to in the calling scope.
FollowEl(x, s);
If you call
FollowEl.call(foo, x, s)
, or
FollowEl.apply(foo, [x, s])
, then
this
will refer to the first argument passed in.
var foo = { id: 42 };
FollowEl.call(foo, x, s);
FollowEl.apply(foo, [x, s]);
If you bind the function to an object, you'll get a new function returned. When you call that new function, it will call the original function, but with the bound object as
this
.
var foo = { id: 42 };
var boundFn = FollowEl.bind(foo);
boundFn(x, s);
If you write it as an arrow function, then it should inherit
this
from the calling scope.
const FollowEl = (N, sets) => {
this.N = N;
this.sets = sets;
};
var foo = {
id: 42,
fn: function(N, sets){
FollowEl(N, sets);
}
};
foo.fn();
However, this doesn't seem to work for me.
this - JavaScript | MDN[
^]
Function.prototype.bind() - JavaScript | MDN[
^]
Arrow function expressions - JavaScript | MDN[
^]
Scope in JavaScript - Digital Web[
^]
In short, you'll need a lot more context before you can convert this to C#. :)