这个特定的构造有名字吗?
例如:
function foo() {
var bar = this.bar = function () {
return "bar";
};
this.mybar = function () {
return bar();
}
}
var myFoo = new foo();
myFoo.bar = function() {
return "notbar";
};
myFoo.bar(); // returns 'notbar'
myFoo.mybar(); // returns "bar"
基本上它允许闭包的内部私有方法,并且只有在外部访问时才可能被覆盖。因此,对于闭包内该函数的引用,对原始函数的引用永远不会改变。但是闭包对象的实例化器可以覆盖该函数,而不会破坏该对象的功能。
这个特定的构造有名字吗?它有用吗?
In example:
function foo() {
var bar = this.bar = function () {
return "bar";
};
this.mybar = function () {
return bar();
}
}
var myFoo = new foo();
myFoo.bar = function() {
return "notbar";
};
myFoo.bar(); // returns 'notbar'
myFoo.mybar(); // returns "bar"
Basically it allows for an internal private method to a closure, with the possibility of being overwritten only for external access. So the reference to the original function never changes, for references of that function within the closure. But instantiators of the closure object can overwrite that function without breaking the functionality of the object.
Is there a name for this particular construct, and is it even useful?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您指的是将函数分配给局部变量并在另一个公共方法中使用该函数,那么是的,这将是某种形式的数据封装。除此之外,我想说没有特殊的名称。
var bar
是函数的本地变量,this.bar
是新对象的属性。变量和属性碰巧具有相同的名称,但它们不相关。仅当您想让
bar
中的函数可公开访问并确保其他函数正确工作(以防公共bar
被覆盖)时,它才有用。所以它是保护其他功能的某种形式,但它不是允许外部覆盖的特殊模式。
如果
this.bar
的唯一目的是被覆盖,那么您可以通过以下方式实现相同的目的:当然,如果您在分配之前调用
myFoo.bar()
一个函数,然后你会得到一个错误。If you refer to assigning a function to a local variable and using this function in another public method, then yes, this would some form of data encapsulation. Apart from that, I'd say there is not special name for that.
var bar
is a variable local to the function andthis.bar
is a property of the new object. The variable and the property happen to have the same name, but they are not related.It is only useful if you want to make the function in
bar
publicly accessible and ensure the correct working of the other function, in case the publicbar
is overwritten.So it is some form of protecting the other functions, but it is not a special pattern to allow external overwriting.
If the sole purpose of
this.bar
is to be overwritten, then you'd achieve the same with:Of course, if you call
myFoo.bar()
before you assign a function to it, then you will get an error.