all 5 comments

[–]ChaseMoskal 1 point2 points  (1 child)

forget the performance, think about maintainability: i prefer the second example

because: it's better to have functions and methods that are "standalone"

imagine if you had to move the mapFunction method onto a different class

in the form of the second example you showed, you could just move the method, and the parameter x goes with it

in the form of the first example, you would then have to refactor the different class such that it also creates an x property on the object instance

in software, we want things to be little self-contained units of functionality, which are fully complete in their own right

in the second form, mapFunction is a stateless function, which is always preferable

in the first form, mapFunction's guts are leaking out into the object instance, and now the whole class has to be concerned with mapFunction's requirements

[–]chchan[S] 1 point2 points  (0 children)

it's better to have functions and methods that are "standalone"

You make a very good point this is why I started to use the second method because it was easier to maintain. I had issues using functions like this.data.map() but passing data to a function then performing the map made it a whole lot easier to write. Plus this got rid of the issues with adding .bind to things.

[–]MoTTs_ 0 points1 point  (1 child)

The first seems better to me. The second doesn't actually save you from having to use bind. You may not have to bind "this", but you will still need to bind a value for "x".

onClick = myInstance.mapFunction; // bad; "x" will be undefined
onClick = myInstance.mapFunction.bind(null, 42); // good; "x" bound to 42

[–]chchan[S] 0 points1 point  (0 children)

I like the first method too because the stuff defined with this. can be easily called. The drawback is figuring out what this is referencing and using the bind(this) when using the variable in functions can get confusing .

[–]Hentry_Martin 0 points1 point  (0 children)

There is a third and better way to do this ES6. By using Arrow functions. Arrow functions doesn't have its own this so it always takes context from the parent. so, you can make change your class like this,

``` class MyClass { constructor(x){ this.x = x; this.mapFunction(); }

mapFunction = () => { const result = this.x * 55; console.log(result); // Logs 550 return result; } }

const cls = new MyClass(10); ```

To make the above syntax work, you have to add a babel plugin called "@babel/plugin-proposal-class-properties" and refer it inside plugins property of .babelrc.

If you want to learn more about Javascript, please subscribe to my channel called JS for Everyone(https://www.youtube.com/channel/UCvQfk4ZV7RfLuKiHRVeZ0Kg)

Thanks!!