Click here to Skip to main content
15,879,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
JavaScript
var FollowEl = function(N, sets) {
  this.N = N;
  this.sets = sets;
};


This is a global function in a javascript .js file. It doesn't have a prototype associated with it so i can't readily translate it to a C# struct or class?

I'm trying to port it to C# but I can't tell what "this" refers to, or if the definition is better treated as a class or a delegate, or what?

If this isn't enough code to answer the question please let me know, as I only know javascript in fits and starts. I use it when I have to, but my background is C++ and C#

What I have tried:

I don't know what to try because I can't tell what this is? Is it a delegate basically? what is "this?"

My thought is this is basically a delegate returning a tuple with (N, sets) but i can't be sure
Posted
Updated 7-Feb-20 7:24am
v2

1 solution

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.
JavaScript
FollowEl(x, s); // this === window

If you call FollowEl.call(foo, x, s), or FollowEl.apply(foo, [x, s]), then this will refer to the first argument passed in.
JavaScript
var foo = { id: 42 };
FollowEl.call(foo, x, s); // this === foo
FollowEl.apply(foo, [x, s]); // this === foo

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.
JavaScript
var foo = { id: 42 };
var boundFn = FollowEl.bind(foo);
boundFn(x, s); // this === foo


If you write it as an arrow function, then it should inherit this from the calling scope.
JavaScript
const FollowEl = (N, sets) => {
    this.N = N;
    this.sets = sets;
};

var foo = {
    id: 42,
    fn: function(N, sets){ 
        FollowEl(N, sets); 
    }
};

foo.fn(); // this === foo
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#. :)
 
Share this answer
 
v2
Comments
honey the codewitch 7-Feb-20 13:41pm    
Thanks so much. I figured out what it was doing, I think, and converted it to a struct which *should* work. *knock on wood*
Maciej Los 7-Feb-20 13:47pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900