简体   繁体   English

创建JavaScript对象的最佳方法

[英]Best way to create javascript objects

all i have seen creating objects like below, what is this type creating object actually? 我所看到的创建对象的方式如下所示,这种类型的创建对象实际上是什么?

var myApp = myApp || {};

I'm creating object like this 我正在创建这样的对象

var myApp={property:"value",method:function(){}};

Can anybody please tell me the difference between both type. 谁能告诉我两种类型之间的区别。

The first example won't replace the variable myApp if it already exists, and is useful for working in unfamiliar namespaces or when working with global variables. 第一个示例不会替换变量myApp如果已存在),并且对于在不熟悉的名称空间中工作或在使用全局变量时很有用。 You will have to specify myApp 's properties after creation. 创建后,您将必须指定myApp的属性。

The second example will always create a new version of myApp and allows you to specify its properties during creation. 第二个示例将始终创建新版本的myApp并允许您在创建过程中指定其属性。 It will override any other variables already named myApp . 它将覆盖已经名为myApp所有其他变量。

Both examples create the same 'type' of object--there is only actually one type of object. 两个示例都创建相同的“类型”对象-实际上只有一种类型的对象。 What makes objects different from each other is the properties they possess. 使对象彼此不同的是它们拥有的属性。

The first example assigns a value to itself if it already has a true value, and an object with no properties otherwise. 第一个示例为其自身分配一个值(如果已经具有一个真值),否则为一个没有属性的对象分配一个值。

The second example assigns an object with properties. 第二个示例为对象分配属性。

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

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