doglin
doglin

Reputation: 1741

How to define an instance in javascript

Hi I see this line of code

CtvDfpAd.GetInstance = function () {
    if (!CtvDfpAd.__instance) {
        CtvDfpAd.__instance = new CtvDfpAd();
    }

    return CtvDfpAd.__instance;
};

is "instance" a keyword in javascript? i searched online, i don't believe it is, can someone explain?

Thanks

Upvotes: 0

Views: 305

Answers (3)

Tmdean
Tmdean

Reputation: 9309

No, __instance is not a keyword. The double-underscore prefix appears to be a convention to treat the member variable as private, since JavaScript has no concept of private variables.

This code is an implementation of the Singleton pattern in JavaScript. A singleton class means that it is designed to have only one instance throughout the lifetime of the program. This function checks if the instance exists - if it does, it returns it. Otherwise it creates one and returns the new instance.

Upvotes: 4

Dan Prince
Dan Prince

Reputation: 29999

Looks like instance is just a protected property of that CtvDfpAd object. Looks like it might be a singleton based on the pattern exhibited here:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

You'll almost certainly get a better idea of what that code is doing by reading that article, but in short, what this code is doing:

  • If there is already an instance of our singleton, return it.
  • Otherwise create a new instance of this object and return that.

Upvotes: 1

ktm5124
ktm5124

Reputation: 12123

instanceof is a keyword in JavaScript. Apart from that, it's a technical term in object-oriented programming. The code you posted uses a common pattern for instantiating objects

Upvotes: 1

Related Questions