开发者

What is a good approach to be able setting function to object in JavaScript?

//namespace
if (!window.SlidePanel) {
    window.SlidePanel = (function () {
        var SlidePanel = {};

        return SlidePanel;
    })();
}   

SlidePanel.panel = function (el) {
    this.$ = el;
}
SlidePanel.panel.prototype = {
    insert: function () {
    },
    show: function () {
    },
    hide: function () {
    }        
}

SlidePanel.up = new SlidePanel.panel($('div#up-panel'));
SlidePanel.bottom = new SlidePanel.panel($('div#bottom-panel'));
SlidePanel.left = new SlidePanel.panel($('div#left-panel'));
SlidePanel.right = new SlidePanel.panel($('div#right-panel'));

I want to be able to set show and hide functions in some place of code. I thought to add setShowFn and setHideFn function to SlidePanel.panel.prototype like this

  SlidePanel.panel.prototype = {
        ...
        setShowFn: function (fn) {
            this.show = fn;
        },
        setHide开发者_JAVA技巧Fn: function (fn) {
            this.hide = fn;
        }
  }

Is this a good approach or there is more elegant way to do this?


If you want to override the show or hide function on just one instance of a SlidePanel.panel, you're free to just update that instance:

SlidePanel.up.show = function() { /* ... */ };

That breaks the inheritance of show for that specific instance, without changing any other instances that still use the show property from the prototype.

If you want to update show for all instances that are using the inherited version, you can do this at any time:

SlidePanel.panel.prototype.show = function() { /* ... */ };

...since the instances have a reference back to the prototype, and so changes to the prototype happen "live." Note that any instance on which you've done the first example above will be unaffected, because it's not using the version of show from the prototype anymore.

And yes, you're free to encapsulate this in your setShowFn and setHideFn functions if you want to; just be aware that there's nothing other than convention/documentation preventing code from assigning to the properties directly even if you do.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜