Summary of JavaScript Objects

There are seven data types in js: undefined, null, Boolean, Number, String, Object, Symbol (es6). Recently, I have a clearer understanding of objects in js, so let's summarize:

1. Objects have their own private properties

//json有自己的私有属性
var json =new Object();
json.a = 20;
console.log(json.a); //20

//变量(不是对象)没有私有属性
var json2;
json2.a=10;
console.log(json2.a); //undefined

2. As long as it is new, it is an object

Why are all objects coming out of new? We all know that there are three ways to define number and string. Let's take Number as an example:

//定义Number的两种方法
var a = 1;
var a = Number(1)
var a = new Number(1);

We test the difference between the two ways, the ordinary way of defining number:

var a = 1;
a.b = 3;
console.log(typeof a); //输出类型为number
console.log(a.b); //undefined
var a = Number(1);
a.b = 3;
console.log(typeof a); //输出类型为number
console.log(a.b); //undefined

When we create a number as new:

var a = new Number(1);
console.log(typeof a); //输出类型为object

//此时我们给a加一个私有属性
a.b = 3;
console.log(a.b);//输出3

3. Different objects are definitely not equal

//变量相等时输出true
var a = 'abc';
var b = 'abc';
console.log(a == b); //true
//数组为对象,对象相等时输出false
var a = [10];
var b = [10];
console.log(a == b);//false

//new出的对象相等时,输出false
var a = new String('abc');
var b = new String('abc');
console.log(a == b); //false

4. Objects will have a reference mechanism

Objects have a reference mechanism

var a = {};
b =a;
b.c=10;
console.log(a); //输出 {c:10}
/*其实很好理解,当创建aa独自占用一块内存
 *随后b = a 这时b和a公用一块内存
 *b.c =10 相当于在这块内存里加入了数据c:10
 *所以最后输出的a为{c:10}这就是一个简单的引用机制
*/

If you don't want to refer to it, you can reassign it.

We can't judge whether it is an object based on typeof, such as null and undefined. Although typeof comes out as object type, they do not have the properties of objects and do not belong to objects.

The above are some of my understanding of the object, if there are any mistakes, please correct them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651008&siteId=291194637