简体   繁体   English

如何从JavaScript中的函数解除绑定?

[英]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. 我将此绑定到resize函数,但如何从resize函数中删除或取消绑定。 I am binding this in some frequently calling method and every time I want to clear this from resize function before bind this. 我在一些经常调用的方法中绑定它,并且每次我想在绑定它之前从resize函数中清除它。 I want bind this to resize function but only time, this can be used in setInterval. 我想绑定这个来调整函数但只有时间,这可以在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: bind()创建一个新函数时,您可以执行以下操作:

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. 因此,该方法不是“绑定”,当您调用bind()您正在创建一个函数,而不是编辑原始的一个上下文。

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. bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值,并在调用新函数时提供任何前面提供的给定参数序列。

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 参考: 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 取消绑定this和再次使用.bind绑定this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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