underscore的bind和bindAll方法

看風景就發表於2018-05-12

bind方法和bindAll方法都是用來設定函式的this值的,區別是呼叫方式不同。

var xiaoming = {
    say:function(){
        console.log('I am xiaoming');
    }
}

//bind
var func = bind(xiaoming, xiaoming.say);
func(); // I am xiaoming

//bindAll
bindAll(xiaoming, 'say');
var func = xiaoming.say;
func(); // I am xiaoming

bind和bindAll都是改變函式的this指向,然後返回一個新的函式,永久的指向這個this指向

舉例

function Person(name,age){
    this.name = name;
    this.age = age;

    bindAll(this, 'sayName', 'sayAge');
}

Person.prototype.sayName = function(){
    console.log(this.name);
}

Person.prototype.sayAge = function(){
    console.log(this.age);
}

var person = new Person('xiaoming',26);
var func = person.sayName;
func();

$('button').click(person.sayAge);

無論如何呼叫,sayName和sayPerson的this都指向person物件。

相關文章