I have below code.
var person1 = {
fname: 'Cristiano',
lname: 'Ronaldo',
getName: function() {
return this.fname + ' ' + this.lname;
}
}
var person2 = {
fname: 'Luka',
lname: 'Modric',
getName: function() {
return this.fname + ' ' + this.lname;
}
}
var logname = function() {
console.log(this.getName());
}.bind(person1); // not working as expected when .bind() here !!!
var newlogname1 = logname.bind(person1);
newlogname1(); // prints 'Cristiano Ronaldo'
var newlogname2 = logname.bind(person2);
newlogname2(); // prints 'Cristiano Ronaldo'
var person1 = {
fname: 'Cristiano',
lname: 'Ronaldo',
getName: function() {
return this.fname + ' ' + this.lname;
}
}
var person2 = {
fname: 'Luka',
lname: 'Modric',
getName: function() {
return this.fname + ' ' + this.lname;
}
}
var logname = function() {
console.log(this.getName());
}.bind(person1); // not working as expected when .bind() here !!!
var newlogname1 = logname.bind(person1);
newlogname1(); // prints 'Cristiano Ronaldo'
var newlogname2 = logname.bind(person2);
newlogname2(); // prints 'Cristiano Ronaldo'
But if I change the below code snippet, it will work as I expected.
var logname = function() {
console.log(this.getName());
};
var person1 = {
fname: 'Cristiano',
lname: 'Ronaldo',
getName: function() {
return this.fname + ' ' + this.lname;
}
}
var person2 = {
fname: 'Luka',
lname: 'Modric',
getName: function() {
return this.fname + ' ' + this.lname;
}
}
var logname = function() {
console.log(this.getName());
};
var newlogname2 = logname.bind(person2);
newlogname2();
var newlogname1 = logname.bind(person1);
newlogname1();
What is this behavior ? What happens when I .bind()
just in the declaration part of it. Can't I change what this
supposed to mean when the function runs if I do like that.