开发者

Is there a name for this particular construct?

开发者 https://www.devze.com 2023-02-10 14:09 出处:网络
In example: function foo() { var bar = this.bar = function () { return \"bar\"; }; this.mybar = function () {

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. Bu开发者_C百科t 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?


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 and this.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 public bar 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:

function foo() {
    var 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"

Of course, if you call myFoo.bar() before you assign a function to it, then you will get an error.

0

精彩评论

暂无评论...
验证码 换一张
取 消