In-depth understanding of the first part of the javascript object series - first understanding of objects

First, the definition of the object

The basic data types of javascript include undefined, null, boolean, string, number and object. Unlike other primitive values, an object is a composite value: it aggregates many values ​​(primitives or other objects) that can be accessed by name.
Therefore, an object can also be seen as an unordered collection of properties, each of which is a name-value pair. Property names are strings, so we can think of objects as maps from strings to values.

2. 3 ways to create objects

There are three main ways: new constructor, object literal, and Object.create() function.
[1]: new constructor
Use the new constructor followed by the Object() constructor to initialize a newly created object.

var person = new Object();
//如果不给构造函数传递参数可以不加括号 var person = new Object;
person.name = 'bai';
person.age = 29;
//创建无属性的空对象
var cody1 = new Object();
var cody2 = new Object(undefined);
var cody3 = new Object(null);
console.log(typeof cody1,typeof cody2, typeof cody3);//object object object

If the parameter is an object, this object is returned directly.

var o1 = {a: 1};
var o2 = new Object(o1);
console.log(o1 === o2);// true

//函数也是一种特殊的对象。
var f1 = function(){};
var f2 = new Object(f1);
console.log(f1 === f2);// true

If it is a primitive value, the wrapper object corresponding to the value is returned.

//String {0: "f", 1: "o", 2: "o", length: 3, [[PrimitiveValue]]: "foo"}
console.log(new Object('foo'));

//Number {[[PrimitiveValue]]: 1}
console.log(new Object(1));

//Boolean {[[PrimitiveValue]]: true}
console.log(new Object(true));

If the Object() function is used directly without new, it is equivalent to the conversion method, which can convert any value into an object.
[Note]: undefined and null will be converted to an empty object.

var uObj = Object(undefined);
var nObj = Object(null);
console.log(Object.keys(uObj));//[]
console.log(Object.keys(nObj));//[]

If the parameter of Object() is an object, the original object is returned directly.

var o = {a:1};
var oObj = Object(o);
console.log(Object.keys(oObj));//['a']

Using this, you can write a function that determines whether a variable is an object.

function isObject(value) {
  return value === Object(value);
  //如果是一个对象,那么Object(value)必定返回原对象,所以最终会返回true.
}
isObject([]) // true
isObject(true) // false

[2]: Object literals
JavaScript provides a shortcut called literals for creating most native objects. Using literals just hides the same basic process as using the new operator.
An object literal is a mapping table consisting of several name-value pairs. The name-value pairs are separated by colons, and the entire mapping is enclosed in curly braces.
Different attributes are separated by commas, the attribute name can be any string, the attribute value can be any type of expression, and the value of the expression is the attribute value.

//等价于var person = new Object();
var person = {}; 
var person = {
    name : 'bai',
    age : 29,
    5 : true
};

Use object literals to define objects, and property names are automatically converted to strings.

//同上
var person = {
    'name' : 'bai',
    'age' : 29,
    '5' : true
};

[Note] In general, the comma after the last property of an object literal is ignored, but causes an error in IE7-browser.

//IE7-浏览器中报错 SCRIPT1028: 缺少标识符、字符串或数字
var person = {
    name : 'bai',
    age : 29,
: true,
};

[3]: Object.create()
ES5 defines a method called Object.create(), which creates a new object. The first parameter is the prototype of the object, and the second optional parameter is used to create a new object. properties are further described.

var o1 = Object.create({x:1,y:1}); //o1继承了属性x和y
console.log(o1.x);//1

It is possible to create an object without a prototype by passing in the parameter null, but an object created this way will not inherit anything, not even the underlying methods. Such as toString() and valueOf().

var o2 = Object.create(null); // o2不继承任何属性和方法
var o1 = {};
console.log(Number(o1));//NaN
console.log(Number(o2));//Uncaught TypeError: Cannot convert object to primitive value

If you want to create an ordinary empty object (such as an object created by {} or new Object()), you need to pass in Object.prototype.

var o3 = Object.create(Object.prototype); // o3和{}和new Object()一样
var o1 = {};
console.log(Number(o1));//NaN
console.log(Number(o3));//NaN

The second parameter of the Object.create() method is the property descriptor.

var o1 = Object.create({z:3},{
  x:{value:1,writable: false,enumerable:true,configurable:true},
  y:{value:2,writable: false,enumerable:true,configurable:true}
}); 
console.log(o1.x,o1.y,o1.z);//1 2 3

Third, the composition of the object.

An object is an unordered collection of key-value pairs, consisting of key names and property values.
[Key name]: All key names of the object are strings, so they can be added without quotation marks. If they are not strings, they will be automatically converted into strings.

var o = {
  'p': 'Hello World'
};
var o = {
  p: 'Hello World'
};

[Note]: If the key name is not a valid identifier, it must be enclosed in quotation marks, otherwise an error will be reported.

//Uncaught SyntaxError: Unexpected identifier
var o = {
    1p: 123
}

var o = {
    '1p': 123
}

[Attribute value]: The attribute value can be any type of expression, and the result of the final expression is the result of the attribute value.

var o ={
    a: 1+2
}
console.log(o.a);//3

If the property value is a function, then we call the property a "method".

var o = {
  p: function (x) {
    return 2 * x;
  }
};
o.p(1);//2

Since the methods of objects are functions, they also have a name attribute. The name property of a method returns the function name immediately following the function keyword. If it is an anonymous function, the ES5 environment will return undefined, and the ES6 environment will return the method name.

var obj = {
  m1: function f() {},
  m2: function () {}
};
obj.m1.name // "f"
obj.m2.name //ES5: undefined
obj.m2.name //ES6: "m2"

Fourth, the reference object

If different variable names point to the same object, then they are all references to this object, that is, point to the same memory space. Modifying one of these variables will affect all other variables.

var o1 = {};
//简单类型传值,复杂类型传地址。
var o2 = o1;

o1.a = 1;
console.log(o2.a);// 1
o2.b = 2;
console.log(o1.b);// 2

If you cancel a variable's reference to the original object, it will not affect the other variable.

var o1 = {};
var o2 = o1;

o1 = 1;
console.log(o2);//{}

5. Instance methods of objects

valueOf(): used to return the current object.
var o = new Object();
o.valueOf() === o // true
toString(): Returns the string form corresponding to the current object.
var o1 = new Object();
o1.toString() // "[object Object]"

var o2 = {a:1};
o2.toString() // "[object Object]"

Generally, use Object.prototype.toString() to obtain the class attribute of the object for type identification.

toLocaleString(): The toLocaleString() method does not do any localization itself, it just calls the toString() method and returns the corresponding value.
var o = {a:1};
o.toLocaleString() // "[object Object]"

6. Three methods for judging that the object is empty

1. For-in statement
let isEmpty = (obj) => {
  for(let i in obj){
    //哪怕只遍历一次,也可证明对象不为空。
    return false
  }
  return true
}
console.log(isEmpty({}))//true
console.log(isEmpty({a:1}))//false
2. JSON.stringify method
let isEmpty = (obj) => {
  return JSON.stringify(obj) === '{}'
  //JSON.stringify:用于将一个对象变成字符串,然后与'{}'对比。
}
console.log(isEmpty({}))//true
console.log(isEmpty({a:1}))//false
3. Object.keys method
let isEmpty = (obj) => {
  return !Object.keys(obj).length
  //从属性名的长度上进行判读,属性名长度为0,则取反为1,证明是一个空对象。
}
console.log(isEmpty({}))//true
console.log(isEmpty({a:1}))//false

Reprinted from: Little Match's Blue Ideal
http://www.cnblogs.com/xiaohuochai/p/5613593.html
When reading the teacher's blog, I treat it as a book, so most of my blogs come from the teacher's blog The original words and examples, plus some of my own understanding, and made appropriate annotations, and some tests on the teacher's code.

Guess you like

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