The argument against Typescript is that the following code:
Produces the output
Hello, undefined and not
The most obvious way, and best practice, to fix it in Typescript is to use arrow functions:
This will output
Hello, world as expected.
.bind() we create a new function where the
this keyword is bound to the given value. Here is how it would look in the previous example:
When declaring the varible
unbound and assigning the function
greeter.greet() to it, we create a new function with
.bind() where we bind
greeter instead of
unbound. The function is not executed until the very last line;
.apply() is more or less the same thing, just that
.call() takes single arguments while
.apply() takes an array as argument.
Take a look first on the code and see if you can understand the differens between
Did you figure out the differens?
.bind() creates a new function and bind
this to whatever we want whereas
.call() set the value of
this when it is actually called (hence the name, I guess). This way we can later call
unbound but whit a new value for
this, something we can’t do if we used
Passing arguments when using
First, let us change the
greet function a bit:
What do you think the following code will produce as an output?
It will actually output
Hello, world!! since we passed two
"!" as arguments when we created the function with
.bind(). If we instead don’t pass any arguments we can get the result we propable where hoping for:
That code will output the expected
Similar, if we want to pass an argument when using
.apply() we can easily do that as well:
As you see, when using
.call() we pass the arguemnts one by one but when using
.apply() we pass them as an array.
Using arrow functions we can create an anonymous function where
this is bound in the same way as when using
The output would be
Hello, world, just as expected. Arrow functions is a neat feature introduced in ES2015.
this lets us share methods between objects, that is why it behaves kinda strange, so if you want to use the
Array.prototype.forEach function somewhere else you can;
MyList.prototype.forEach = Array.prototype.forEach. However, if you remove
this you no longer can do that. Anyway, here is what it would look like without
or by using block scope:
Hello, world is the output. This might be the easiest way if you are ok with the drawbacks. But even Crockford avoids
this. But I don’t like him so I use
this and Typescript! :)
The real problem with
The code above will actually put
That’s better. The difference is that we added the
new keyword. That’s another keyword Crockford avoids because as you can see it is really easy to put stuff globaly unintended when using
this and (not using)
Hope you learned something new!