简体   繁体   English

我如何摆脱将“新功能”放在功能之前的问题

[英]How can i get rid of putting “new” before a function

I was wondering how can I make it posible to get rid of putting "new" before a function, for example: 我想知道如何才能摆脱在函数之前放置“ new”的可能性,例如:

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

is there a posible way of doing this without the "new"? 没有“新”,有没有办法做到这一点?

here is the code I'm trying to use without the "new": 这是我尝试使用的没有“ new”的代码:

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));
    };
};

and here's what I would have to do to invoke the function: 这是调用该函数所要做的:

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

This is possible by checking whether this is an instance of the function itself and returning a new instance otherwise: 通过检查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));
    };
};

You could use JavaScript closures. 您可以使用JavaScript闭包。 In particular look at the "Using Closures for the Module Pattern" section of this webpage for a full description. 特别是,请参阅本网页的“使用模块模式的闭包”部分以获取完整说明。 The idea is to have the function return an literal with all the required methods. 想法是让函数返回带有所有必需方法的文字。 Any functions or variables that you want to be kept private are just local variables for the function. 您想要保留为私有的任何函数或变量都只是该函数的局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM