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?

1
  • 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)). Commented Jan 11, 2015 at 5:02

5 Answers 5

32

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

talk.bind(p)();

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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)();

Comments

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/

Comments

1

call or apply can be used instead of bind

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.