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.

1 Answers

1
ııı On Best Solutions

.bind() only works if the function you're binding isn't already bound:

function f() {
  console.log(this.a)
}

const f_1 = f.bind({a: 1}) // As expected
const f_2 = f.bind({a: 2}) // -Ditto-
const f_2_3 = f_2.bind({a: 3}) // f_2 already bound, can't .bind() to other object

f_1()
f_2()
f_2_3()

/** Check if function is bound, as per @str's comment */
function isBound(fun) {
  return !('prototype' in fun)
}

console.log(
  isBound(f),
  isBound(f_1)
)

Update: Added way to check if function is already bound, as per @str's comment below