16

function:

function talk(){ 
        console.log(this.name + " dice: ");
}

var Person = function(name, surname){
    this.name = name;
    this.surname = surname;
}

var p = new Person("Mark", "Red");

talk.bind(p);

what's wrong with bind?

Donovant
  • 3,091
  • 8
  • 40
  • 68
  • Worth adding, for anyone following this question, that you can get "one-time" binding by using a function's `call` or `apply` method. So another solution to the above issue is to replace `.bind` with `.call` (here `talk.call(p)`). – Platinum Azure Jan 11 '15 at 05:02

5 Answers5

31

It does work, talk.bind(p) returns the bound function:

talk.bind(p)();

Rob M.
  • 35,491
  • 6
  • 51
  • 50
8

Nothing is wrong with bind()-- it's just not being used correctly. bind() returns a new function which is bound to the object specified. You still need to execute that function:

function talk(){ 
        console.log(this.name + " dice: ");
}

var Person = function(name, surname){
    this.name = name;
    this.surname = surname;
}

var p = new Person("Mark", "Red");

var markTalks = talk.bind(p);

markTalks();    // logs properly
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
2

There is nothing wrong with bind, it returns a function which is bound to the object passed as argument. So you need to invoke it like this

talk.bind(p)();
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

As mentioned by others, bind appears to work as expected but it needs invoking.

Another solution that is a bit cleaner, especially if each 'Person' object needs the ability to talk, would be to include the function in the person constructor:

var Person = function(name, surname){
    this.name = name;
    this.surname = surname;
    this.talk = function(){
        console.log(this.name + " dice: ");
    }
}

var p = new Person("Mark", "Red");

p.talk();

See this fiddle: http://jsfiddle.net/amspianist/J5BSh/

Josh Taylor
  • 532
  • 2
  • 8
1

call or apply can be used instead of bind

talk.call(p); talk.apply(p);

Scott Wager
  • 758
  • 11
  • 9