How to define an instance in javascript

如何在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?

Thanks

我看到这行代码

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

    return CtvDfpAd.__instance;
};

“实例”的关键字在JavaScript中?我在网上查了,我不相信它是,谁能解释?

感谢

最佳答案 (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.

不,__instance不是关键字。双下划线前缀的似乎是一个公约对成员变量为私有,因为JavaScript没有私有变量的概念。

本代码是用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

实例是JavaScript中的关键词。除此之外,它是面向对象的编程技术术语。你把代码使用的通用模式实例化对象

答案 (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:

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.

看起来像实例就是一个受保护的属性,ctvdfpad对象。看起来像是一个单独的基于模式表现出这里:

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

你几乎肯定会获得一个更好地了解这些代码是做阅读这篇文章,但总之,这个代码是做什么:

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

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/22077311