Frage

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?

War es hilfreich?

Lösung

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

talk.bind(p)();

Andere Tipps

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

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

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/

call or apply can be used instead of bind

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top