简体   繁体   中英

How to unbind this from a function in javascript?

I'm binding this to resize function, but how to remove or unbind this from a resize function. I am binding this in some frequently calling method and every time I want to clear this from resize function before bind this. I want bind this to resize function but only time, this can be used in setInterval.

function resize() {
 // some process
}
// I want to unbind this from resize, before going to bind again
resize = resize.bind(this);

As bind() creates a new function, you can do the following:

function resize() {
 // some process
}

// Bound
const boundResize = resize.bind(this);

// Unbound
const unboundresize = resize;

Thus the method is not "bound", when you invoke bind() you are creating a new function, not editing the original one context.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

You can use

resize = resize.bind(undefined)

to unbind the this and the again use .bind to bind this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM