I was reading this page just to brush up on .apply
syntax, and I realized I had a gap in my JS knowledge:
You can change the value of this
in a function by using .bind
and also .apply
(I assume .call
follows same rules as .apply
so I'll not talk about that separately). So I wanted to know, if I use .bind
and then call it with .apply
, which will take precedence?
So I just yoinked the example from w3schools and modified it:
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName: "John",
lastName: "Doe"
}
var person2 = {
firstName: "Mary",
lastName: "Anne"
}
fn = person.fullName.bind(person2);
console.log(fn.apply(person1, ["Oslo", "Norway"]));
So if it prints Mary Anne, the value of this
given by .bind
takes precedence over the value given by .apply
.
And it did! Marry Anne was printed. So that leaves me wondering if there are any other rules regarding this
that I don't quite understand. For example, can you rebind after calling .bind
?