开发者

Is this 'ok' practice in Javascript?

I have a wrapper function in JavaScript that provides some helpful methods for a .Net control embedded in a web page. In order to enjoy the benefits of intellisense, I'd like to re-wrap the control each time I use the wrapper. (If I wrap it once and set it in a global variable, I lose intellisense the next time I use it in another function - at least in Visual Studio 2008):

function onLoad() {
    var control = new Wrapper(form1.button1);
    control.SetColor("Red");
    // etc.
}

function onButton_Clicked() {
    var control = new Wrapper(form1.button1);
    control.SetBackColor("Blue");
    // etc.
}

So, to avoid re-creating the wrapper each time for the same control, I first check if it's already been created, and if so return that instance. Below is the pseudo JavaScript code:

function Wrapper(control) {

    var i = Wrapper.Controls.IndexOf(control);
    if (i >-1) { return Wrapper.Wrappers[i] };

    // Init stuff

    Wrapper.Controls.Push(control);
    Wrapper.Wrappers.Push(this);

}

Wrapper.prototype.SetColor = func开发者_StackOverflow社区tion(color) {}
Wrapper.prototype.SetBackColor = function(color) {}
...

Wrapper.Controls = new Array();
Wrapper.Wrappers = new Array();

If it is OK to do what I'm doing? Is there a way to make the static variables, Wrapper.Controls & Wrapper.Wrappers, private?


Rather then interaction with .NET controls. (No clue what AFWebControl is) I recommend you interact with the DOM instead.

You can use a DOM manipulation library or raw js.

document.getElementById(id).style.color = ...;

or

$("#id").css("color", ...)

Wait. Is this server-side javascript using ASP ? Please do mark it as serverside if it's so.

To actually answer your question:

var cachedfunction = (function() {
    var cache = {};

    return function(arg) {
        return cache[arg] || (cache[arg] = expensivefunction(arg));
    }

}());

Here we create a dynamic function with a local cache variable in scope. The function either returns the object from the cache or sets the object in the cache (by expensive call) then returns it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜