need explanation of the _.bindAll() function from Underscore.js

前端 未结 3 1088
日久生厌
日久生厌 2021-01-29 21:41

I\'ve been learning some backbone.js and I\'ve seen plenty of instances where _.bindAll() is used. I have read through the entire backbone.js and underscore.js docu

3条回答
  •  忘了有多久
    2021-01-29 22:02

    var Cow = function(name) {
        this.name = name;
    }
    Cow.prototype.moo = function() {
        document.getElementById('output').innerHTML += this.name + ' moos' + '
    '; } var cow1 = new Cow('alice'); var cow2 = new Cow('bob'); cow1.moo(); // alice moos cow2.moo(); // bob moos var func = cow1.moo; func(); // not what you expect since the function is called with this===window _.bindAll(cow1, 'moo'); func = cow1.moo; func(); // alice moos

    Unfortunately the actual "bind all" functionality only works on functions right on the object. To include a function that is defined on the prototype you need to pass those function names explicitely as additional arguments to _.bindAll().

    Anyway, you wanted an explanation: Basically it allows you to replace a function on an object with a function that has the same name and behaviour, but is also bound to that object, so this === theObject even without calling it as a method (theObject.method()).

提交回复
热议问题