我如何摆脱在功能之前放置“新”

时间:2015-02-07 00:51:12

标签: javascript

我想知道如何摆脱在函数之前放置“new”,例如:

new functionToDo("thingsToDo").iGotYouBruh("Halo Humans");

在没有“新”的情况下有没有可行的方法呢?

这是我在没有“新”的情况下尝试使用的代码:

function local (title) {
    var storeTitle = title;
    this.addL = function(lString) {
        var storeText = lString;
        localStorage.setItem(storeTitle, storeText);
        console.info("Locally stored " + storeTitle.toUpperCase() + " with " + storeText.substring(0, 10) + "... As text.");
    };
    this.removeL = function() {
        localStorage.removeItem(storeTitle);
        console.info("Locally removed " + storeTitle + ".");
    };
    this.getL = function () {
        localStorage.getItem(storeTitle);
        console.info("Locally got string of " + storeTitle + ": " + localStorage.getItem(storeTitle));
    };
};

以下是调用该函数所需要做的事情:

new local("storedElement").getL();

2 个答案:

答案 0 :(得分:3)

这可以通过检查this是否是函数本身的实例并以其他方式返回新实例来实现:

function local (title) {
    if (!(this instanceof local)) {
        return new local(title);
    }

    var storeTitle = title;
    this.addL = function(lString) {
        var storeText = lString;
        localStorage.setItem(storeTitle, storeText);
        console.info("Locally stored " + storeTitle.toUpperCase() + " with " + storeText.substring(0, 10) + "... As text.");
    };
    this.removeL = function() {
        localStorage.removeItem(storeTitle);
        console.info("Locally removed " + storeTitle + ".");
    };
    this.getL = function () {
        localStorage.getItem(storeTitle);
        console.info("Locally got string of " + storeTitle + ": " + localStorage.getItem(storeTitle));
    };
};

答案 1 :(得分:1)

您可以使用JavaScript闭包。特别要看一下"使用模块模式的闭包" this webpage部分的完整描述。我们的想法是让函数返回一个包含所有必需方法的文字。您希望保密的任何函数或变量都只是函数的局部变量。