到目前为止,我一直在我的网络应用程序中使用以下语法。
function.bind( obj );
所以假设我有一个像这样的对象:
myObj = {
msg: 'You have logged ',
init: function(){
$( 'input' ).on( 'click', this.log.bind( this ) ),
},
log: function( e ){
console.log( this.msg + $( e.target ).val() );
}
}
我可以调用init
函数。
myObj.init();
但问题是我读到 .bind function() 将被弃用。是 jQuery 绑定(bind)函数还是 JavaScript 绑定(bind)函数将被弃用。
如果这将是即将被弃用的 JavaScript 函数,那么它的替代方案是什么?
最佳答案
But the problem is i read that the .bind function() will be deprecated. Is that the jQuery bind function or the JavaScript bind function that is going to be deprecated.
没有问题,因为您没有使用 $.bind
,而是使用 Function.prototype.bind
If that is going to be the JavaScript function that is going to be deprecated then what is its alternative ?
Function.prototype.bind
并未被弃用。您的代码大部分都很好,除了下面的异常(exception)
有关代码的一些注意事项
// no `var`, `let` or `const` keyword
myObj = {
msg: 'You have logged ',
init: function(){
// event handlers usually pass an `event` object
$( 'input' ).on( 'click', this.log.bind( this ) ),
},
log: function(){ // no `e` param here
console.log( this.msg + $( e.target ).val() );
}
}
可以更新为
var myObj = {
msg: 'You have logged ',
init: function(){
$( 'input' ).on( 'click', this.log.bind( this ) ),
},
log: function(e){
console.log( this.msg + $( e.target ).val() );
}
}
<小时/>
还有一种使用 ES6 表达代码的完全替代方式 – arrow functions有一个词法 this
,因此此示例中不需要 Function.prototype.bind
const myObj = {
msg: 'You have logged ',
init () {
$('input').on('click', event => this.log(event));
}
log (event) {
console.log(this.msg, $(event.target).val());
}
};
关于javascript - 设置上下文时使用绑定(bind)的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577716/