简体   繁体   中英

Is this a OOP in Javascript? How to initialize it internally?

I am using the below Javascript structure but I don't know what do they call this structure? Also, I am unable to initialize variables this way:

(object={}).init();

Structure:

var object=(

    function(){

        function local(){}

        return {
            global: function(){}
        }

    }()
);

Does it consider as OOP in Javscript? A correct approach?

Thank you!

That's called (a variation) of a Module Pattern .

It has to do with OOP in the sense that it deals with something that is normally is one of the attributes of OOP - code encapsulation and (to a much lesser extent) code organization and reuse.

See here .

As for this:

(object={}).init();

that's just ugly unreadable code that should not be written like this. And it will fail, since there is not init method on the object.

This could be called a self invoking function or an immediately invoked function.

This approach can be used in OOP and can be used as an approach to the Singleton pattern.

Try this:

function Object(){
   this.variable = 123;
   this.init = function(){ alert(this.variable);  };
}
var obj = new Object();
obj.init();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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