How to define an instance in javascript


Tags: javascript
标签: javascript

问题 (Question)

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?



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

    return CtvDfpAd.__instance;



最佳答案 (Best Answer)

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.


本代码是用JavaScript Singleton模式的实现。一个单独的类,它的设计了程序的整个一生只有一个实例。此功能检查如果实例存在,如果是这样,它返回。否则,创建一个新的实例并返回。

答案 (Answer) 2

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


答案 (Answer) 3

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:

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.


HTTP:/ / addyosmani。COM /资源/ essentialjsdesignpatterns /书/ # singletonpatternjavascript


  • 如果已经有我们的单例实例,返回。
  • 否则,创建该对象并返回一个新的实例。