search

Home  >  Q&A  >  body text

javascript - Question about bind

When I was reading JS Advanced Programs, Chapter 22 mentioned bind

Why should return be pointed out by the arrow? I don't quite understand it, so when I delete the return pointed by the arrow, the event can also be executed.

曾经蜡笔没有小新曾经蜡笔没有小新2727 days ago780

reply all(4)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-12 09:33:41

    It can be executed, but it cannot only be used in this situation. What if the fn I want to bind is a function that needs to return a value?

    function bind(fn, context){
        return function(){
            return fn.apply(context, arguments);
        }
    }
    function bindNoReturn(fn, context){
        return function(){
             fn.apply(context, arguments);
        }
    }
    var name = 'global';
    function fn(){
        return this.name;
    }
    var bfn = bind(fn, {name:"sf"});
    var bfnNR = bindNoReturn(fn,{name:'return'});
    console.log(bfn());
    console.log(bfnNR());

    reply
    0
  • 阿神

    阿神2017-06-12 09:33:41

    This is the idea of ​​design pattern, return this. I forgot what the pattern is called.
    The other one is the same as the requirement upstairs

    this.do1().do2()

    reply
    0
  • ringa_lee

    ringa_lee2017-06-12 09:33:41

    The purpose of bind is only to bind the function context, which is the this pointer inside the function, and cannot change the original behavior of the function.

    In this example, handleClick has no return value, so it is the same as return. But what if a certain event needs to care about the return value of the event processing function?

    For example, returning false will preventDefault() etc.

    During development, I wrote a return false in handleClick, but it didn’t work. This is the legendary pitfall.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-12 09:33:41

    In your example, the bind function is all side effects...For functions that are all side effects (changing the dom, alerting, sending requests, etc.), it makes no sense for you to return anything.
    The simplest example, when you need to return a value after bind:

    newFn = oldFn.bind(this)
    // ...
    var x = newFn() // undefined

    At this time, the inner return is necessary.

    reply
    0
  • Cancelreply