我经常在插件中看到使用下划线来表示函数是私有的,但仍然允许公共访问(参见下面的示例)。但是为什么呢?我们可以使用.call、.apply或.bind来控制" this“关键字,也可以使用"self”模式,根据这个问题,该模式的速度要快60%:Will Function.prototype.bind() always be slow?
这是懒惰的编程,还是我遗漏了什么?
公开的私有函数示例:
var simplifiedPlugin = function() {
this.name = 'simples';
this._privateFunc = function() {
console.log('Why am I here?');
}
this.publicFunc = function() {
// stuff, then
this._privateFunc();
}
}
var pluginInstance = new simplifiedPlugin();使用自我模式:
var selfSimplifiedPlugin = function() {
var self = this;
this.name = 'self is also simples';
function _privateFunc() {
console.log('Nobody knows am I here');
//I can use self instead of this
}
this.publicFunc = function() {
// stuff, then
_privateFunc();
}
}
var anotherInstance = new selfSimplifiedPlugin();所以,我的重点是使用self模式,私有函数仍然可以使用这个上下文,您只需使用self.fn()而不是this.fn()
发布于 2017-05-24 11:17:08
我这样做的主要原因是更容易调试。
据我所见,当前的JS调试器并不擅长检查闭包符号,特别是当编译器能够很好地优化闭包时。
使用下划线约定,您仍然可以在困难的时候可靠地访问这些“私有”函数,而下划线则表明它们仅用于内部使用。
https://stackoverflow.com/questions/44156236
复制相似问题