Underscore 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

绑定函数

bind:

绑定函数到对象上, 无论何时函数被调用, 函数里的this都指向对象.

    var func = function(greeting){ return greeting + ': ' + this.name };
    func = _.bind(func, {name : 'moe'}, 'hi');
    console.log(func());
    => hi: moe

bindAll:

绑定方法名到对象上, 当这些方法被执行时将在对象的上下文执行. 绑定函数用作事件处理时非常方便, 否则函数调用时 this 关键字根本没什么用.

    var buttonView = {
        label   : 'underscore',
        onClick : function(){ console.log('clicked: ' + this.label); },
        onHover : function(){ console.log('hovering: ' + this.label); }
    };
    var func  = _.bindAll(buttonView, 'onClick', 'onHover');
    func.onClick();
    => clicked: underscore