javascript - Question about bind
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-12 09:31:41
0
4
807

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.

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(4)
过去多啦不再A梦

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());
阿神

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()

左手右手慢动作

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.

phpcn_u1582

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template