简体   繁体   English

为什么 javascript 绑定不起作用

[英]Why javascript bind doesn't work

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?绑定有什么问题?

它确实有效,talk.bind(p) 返回绑定函数:

talk.bind(p)();

Nothing is wrong with bind() -- it's just not being used correctly. bind()没有任何问题——只是没有正确使用。 bind() returns a new function which is bound to the object specified. bind()返回一个绑定到指定对象的新函数 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. bind没有任何问题,它返回一个绑定到作为参数传递的对象的函数。 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.正如其他人所提到的, bind 似乎按预期工作,但它需要调用。

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:另一个更简洁的解决方案,特别是如果每​​个“Person”对象都需要对话的能力,将在 person 构造函数中包含该函数:

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/看到这个小提琴: http : //jsfiddle.net/amspianist/J5BSh/

call or apply can be used instead of bind可以使用call 或 apply代替bind

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM