Previous words
In JavaScript, objects are king; almost everything in JavaScript is an object or works like an object. If you understand objects, you understand Javascript. In JavaScript, a reference type is a data structure used to organize data and functionality together. It is also often called a class. Reference types are sometimes called object definitions because they describe the properties and methods of a class of objects
Most reference type values are instances of the Object type; moreover, Object is also the most commonly used type in JavaScript. Although Object instances don't have much functionality, they are really ideal for storing and transferring data in your application
Create object
There are two ways to create Object types
[1]Object constructor
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 //创建string、number、array、function、boolean、regex console.log(new Object('foo')); console.log(new Object(1)); console.log(new Object([])); console.log(new Object(function(){})); console.log(new Object(true)); console.log(new Object(/\bbt[a-z]+\b/));
[Note] The Object() constructor itself is an object, and the constructor is an object created based on the Function constructor
[2]Use object literals
Javascript provides shortcuts called literals for creating most native object values. Using literals just hides the same
as using the new operatorBasic process
var person = { name : 'bai', age : 29, 5 : true };
[Note] Use commas in object literals to separate different properties, but adding a comma after the last property will cause an error in IE7-
Use the object literal method to define the object, and the attribute name will be automatically converted into a string
//同上 var person = { 'name' : 'bai', 'age' : 29, '5' : true };
If you leave its curly braces empty, you can define an object containing only default properties and methods
//等价于var person = new Object(); var person = {}; [tips]使用对象字面量封装多个可选参数 function displayInfo(args){ var output = ''; if(typeof args.name == 'string'){ output += 'name:' + args.name +'\n'; } if(typeof args.age == 'number'){ output += 'Age:' + args.age + '\n'; } console.log(output); }; displayInfo({ name: 'Nicholas', age: 29 }); displayInfo({ name: 'match' });
The above parameter passing mode is most suitable for situations where a large number of optional parameters need to be passed to the function. Generally speaking, while named parameters are easy to handle, they can be inflexible when there are multiple optional parameters. Therefore, use formal parameters for required values, and use object literals to encapsulate multiple optional parameters
Set object
There are two ways to access object properties. You can use dot notation or bracket notation to get, set or update the properties of an object
The two advantages of the square bracket method are that attributes can be accessed through variables, and attribute names can be Javascript invalid identifiers
[Note] Chinese characters can exist in variables, because Chinese characters are equivalent to characters and are treated the same as English characters, so they can be written as person.白 or person['白']
var myObject = { 123:'zero', class:'foo' }; console.log(myObject['123'],myObject['class']);//'zero' 'foo' console.log(myObject.123);//报错
If the value in square brackets is a non-string type, it will be implicitly converted to a string using String() and then output; if it is a string type, if there are quotes, the original value will be output, otherwise it will be recognized as a variable. If the variable If it is not defined, an error will be reported
person[0] = 1; //[]中的数字不会报错,而是自动转换成字符串 person[a] = 1; //[]中符合变量命名规则的元素会被当成变量,变量未被定义,而报错 person[''] = 2; //[]中的空字符串不会报错,是实际存在的且可以调用,但不会在控制台右侧的集合中显示 person[undefined 或 null 或 true 或 false] = 4;// 不会报错,而是自动转换成字符串 person['白'] = 6; // 不会报错
Delete object
The delete operator can be used to completely delete a property from an object. Delete is the only way to delete a property from an object. Setting a property to undefined or null can only change the value of the property without deleting the property from the object. delete can only delete the data under the object, the other five basic types of values cannot be deleted
[Note] delete will not delete properties found on the prototype chain
var foo = {bar: 'bar'}; delete foo.bar; console.log('bar' in foo);//false var a = 123; delete a; console.log(a);//123
If you declare a variable a in the global state, it is equivalent to a data a under the window object. You can assign a value to a through window.a or a, and the values of window.a and a are always equal, but they cannot be deleted.
var a; a = 10; console.log(a,window.a);//10 10 window.a = 20; console.log(a,window.a);//20 20 delete a ; console.log(a,window.a);//20 20 delete window.a; console.log(a,window.a);//20 20
If you use window.b to declare and assign a value (b is equivalent to declaring it under the window object), you can delete it, and using delete b and delete window.b have the same effect. After deletion, console.log(b) prompts the variable Does not exist, console.log(window.b) prompts undefined
window.b = 10; console.log(b,window.b);//10 10 delete b; console.log(b);//报错 console.log(window.b);//undefined window.b = 10; console.log(b,window.b);//10 10 delete window.b; console.log(b);//报错 console.log(window.b);//undefined
Object nesting
Objects can be nested, but values must be obtained layer by layer
var student = { name : { chinese : 1, englisth : 2 }, sex : 1, age : 26 }
[Note] The value can only be taken layer by layer, such as student.name.chinese, and cannot cross name. Use student.chinese directly, because there may also be elements called chinese under the same level as name
var object1 = { object1_1:{ object1_1_1:{foo: 'bar'}, object1_1_2:{} }, object1_2:{ object1_2_1:{}, object1_2_2:{} } }; console.log(object1.object1_1.object1_1_1.foo);//bar
实例方法
constructor:保存着用于创建当前对象的函数
hasOwnProperty(propertyName):用于检查给定的属性在当前对象实例中(而不是在实例的原型中)是否存在。其中,propertyName必须以字符串形式指定
isPrototypeOf(object):用于检查传入的对象是否是传入对象的原型
propertyIsEnumerable(propertyName):用于检查给定的属性是否能够使用for-in语句来枚举。其中,propertyName必须以字符串形式指定
toLocaleString():返回对象的字符串表示,该字符串与执行环境的地区对应
toString():返回对象的字符串表示
valueOf():返回对象的字符串、数值或布尔值表示,通常与toString()方法的返回值相同
var myObject = { mark: true }; console.log(myObject.constructor);//function Object(){} console.log(myObject.hasOwnProperty('mark'));//true console.log(Object.prototype.isPrototypeOf(myObject));//true console.log(myObject.propertyIsEnumerable('mark'));//true console.log(myObject.toLocaleString());//[object Object] console.log(myObject.toString());//[object Object] console.log(typeof myObject.valueOf(),myObject.valueOf());// object Object{mark:true}
小结:
Object类型
对象其实就是一组数据和功能的集合。对象可以通过执行new操作符后跟要创建的对象类型的名称来创建。而创建Object类型的实例并为其添加属性和(或)方法,就可以创建自定义对象。
var o = new Object();
Object的每个实例都具有下列属性和方法:
● constructor——保存着用于创建当前对象的函数
● hasOwnProperty(propertyName)——用于检查给定的属性在当前对象实例中(而不是在实例的原型中)是否存在。其中,作为参数的属性名(propertyName)必须以字符串形式指定(例如:o.hasOwnProperty("name"))
● isPrototypeOf(object)——用于检查传入的对象是否是另一个对象的原型
● propertyIsEnumerable(propertyName)——用于检查给定的属性是否能够使用for-in语句来枚举
● toString()——返回对象的字符串表示
● valueOf()——返回对象的字符串、数值或布尔值表示。通常与toString()方法的返回值相同。