创建ES6-class实例后,是否可以立即将实例绑定到非静态方法? [英] Can I bind the instance to non-static method immediately after creating instance of ES6-class?
本文介绍了创建ES6-class实例后,是否可以立即将实例绑定到非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以某种方式将前两行组装成一个吗?我不愿意强迫MarkupPreprocessingHelper
的用户写两行...
Is it some way to assemble first two rows into one? I am not feeling comfortable to force users of MarkupPreprocessingHelper
write two rows...
let markupPreprocessingHelper = new MarkupPreprocessingHelper(config);
let preprocessTemplates = markupPreprocessingHelper.takeCareAboutMarkupPreprocessing.bind(markupPreprocessingHelper);
gulp.task('Development run', gulp.series(
preprocessTemplates,
// ...
));
推荐答案
如果制作该函数的反弹副本并将其另存为实例属性,则可以将其传递出去,并且用户无需手动绑定它:
If you make a rebound copy of the function and save it as an instance property, you can then pass it around and users won't need to bind it manually:
function someClass(name){
this.name = name
// make a prebound copy of myFunction
this.preBound = this.myFunction.bind(this)
}
someClass.prototype.myFunction = function(){
console.log(this.name)
}
let p = new someClass("Mark")
// now you can pass a reference of it around without losing the binding
let fn = p.preBound
setTimeout(fn, 500)
这篇关于创建ES6-class实例后,是否可以立即将实例绑定到非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文