This simple construct will create a function that accepts val
as a parameter, and returns val
immediately. We do not need to type return val
, because this is a single-line function.
Identically, we could write
this
without executing the codefunction fDAdder(arr) {
console.log(this);
return arr.reduce((acc, ele) => { return acc + ele; });
};
fDAdder([1, 2, 4, 6]);
If we use a function declaration style function, the this
variable is set to the global
object (i.e. Object [global]
in Node.JS and Window
in your browser).
const adder = (arr) => {
console.log(this);
arr.reduce( (acc, ele) => sum += ele );
};
adder([1, 2, 4, 6]);
In this example, we use a fat arrow style function. Note that when we declare a funciton like this this
becomes
const pokemon = {
firstname: 'Pika',
lastname: 'Chu',
getPokeName: function () {
const fullname = `${this.firstname} ${this.lastname}`;
return fullname;
}
};
console.log(pokemon.getPokeName());
this
const pokemon = {
firstname: 'Pika',
lastname: 'Chu',
getPokeName: function () {
const fullname = `${this.firstname} ${this.lastname}`;
return fullname;
}
};
const logPokemon = pokemon.getPokename.bind(pokemon);
logPokemon('sushi', 'algorithms'); // Pika Chu loves sushi and algorithms
this
refers tofunction Person(name) {
// this.name = name;
// let that = this;
setTimeout(function() {
// console.log(this); // => Window
// console.log(that); // => [Function] => Person
// this.sayName(); // => no method error
that.sayName();
}, 1000);
}
Person.prototype.sayName = function() {
console.log(this.name);
};
const jane = new Person("Jane");