gpt4 book ai didi

javascript - 使用 Function.prototype.bind 或保存的引用

转载 作者:行者123 更新时间:2023-11-29 22:08:34 25 4
gpt4 key购买 nike

这是主观的(基于意见)- 但只是在一定程度上,不要急于结束投票。在工作中引起一些争论,因为每个人都有不同的意见,并且人们试图强制执行一种单一的方法。

简单上下文:当您可以选择在闭包中保存对实例的引用或使用 polyfilled Function.prototype.bind 时,您认为这两种方法有哪些可能的缺点?

为了说明可能的用例,我只是编写了一些类方法。

模式一,保存引用:

obj.prototype.addEvents = function(){
var self = this;

// reference can be local also - for unbinding.
this.onElementClick = function(){
self.emit('clicked');
self.element.off('click', self.onElementClick);
};

this.element.on('click', this.onElementClick);
};

模式二,一个简单的fn.bind:

obj.prototype.addEvents = function(){
// saved reference needs to be bound to this to be unbound
// once again, this can be a local var also.
this.onElementClick = function(){
this.emit('clicked');
this.element.off('click', this.onElementClick);
}.bind(this);

this.element.on('click', this.onElementClick);
};

模式二半,proto方法到事件:

obj.prototype.addEvents = function(){
// delegate event to a class method elsewhere
this.element.on('click', this.onElementClick.bind(this));
};

obj.prototype.onElementClick = function(){
this.emit('clicked');
this.element.off('click', this.onElementClick); // not matching due to memoized bound
};

就我个人而言,我认为没有一种正确的方法可以做到这一点,应该根据具体情况进行判断。我非常喜欢尽可能保存的引用图案。我被告知了。

问题回顾:

是否有任何 GC 问题需要考虑/注意?

对于这两种方法,您是否还有其他明显的缺点或陷阱?

Polyfill 性能或事件原生 .bind 与保存的 ref?

最佳答案

我个人的偏好是使用保存引用的方法。由于 JavaScript 处理 this 的方式,推断 this 的值有时会非常困难。

绑定(bind)很好,但如果您错过了 .bind(this),它看起来就像一个错误。

后者暴露太多;每次需要回调时,您都需要在 API 中公开另一个助手。


有很多方法可以使用原型(prototype)制作。我认为最重要的是选择一个并坚持下去。

关于javascript - 使用 Function.prototype.bind 或保存的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19588234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com