You don't know the JS-object

Source: Internet
Author: User
Tags access properties object object shallow copy hasownproperty

1, the object has two forms definition: declares the literal form and constructs the form.

2. Built-in object: JS has some object subtypes, called built-in objects

var strprimitive = ' I am string '; typeof Strprimitive; // ' String ' instanceof // false var New String (' I am String '); typeof  instanceof  String;   //[object string]

typeof, Instanceof,object.prototype.tostring.call () Distinguishing object types

Object.prototype.toString Method----accurately determine the type of object in JS

1, in JavaScript use typeof to judge the data type, can only distinguish the basic type, namely "number", "string", "Undefined", "Boolean", "Object" five.

For arrays, functions, and objects, their relationships are complex, and using typeof will return the "object" string uniformly.

2, instanceof to determine the type of object, a little trouble

// Object instanceof instanceof instanceof Function) // Array instanceof instanceof Array) // function instanceof instanceof Function)

3. Using the Object.prototype.toString method

Console.log (Object.prototype.toString.call ("Jerry"));//[Object String]Console.log (Object.prototype.toString.call (12));//[Object number]Console.log (Object.prototype.toString.call (true));//[Object Boolean]Console.log (Object.prototype.toString.call (undefined));//[Object Undefined]Console.log (Object.prototype.toString.call (NULL));//[Object Null]Console.log (Object.prototype.toString.call ({name: "Jerry"}));//[Object Object]Console.log (Object.prototype.toString.call (function(){}));//[Object Function]Console.log (Object.prototype.toString.call ([]));//[Object Array]Console.log (Object.prototype.toString.call (NewDate));//[Object Date]Console.log (Object.prototype.toString.call (/\d/));//[Object RegExp]

All types will get different strings, almost perfect.

So why not just use obj.tostring ()?

This is because ToString is a prototype method of object, and a Array function, such as an instance of object, overrides the ToString method. When the ToString method is called by different object types, based on the knowledge of the prototype chain, the corresponding overridden ToString method is called (the function type returns a string that contains the body of the functions, and the array type returns the string consisting of the elements ...). Instead of calling the prototype ToString method on object (which returns the concrete type of the object), obj.tostring () cannot get its object type, only obj is converted to a string type, so when you want to get the concrete type of the object, The prototype ToString method should be called on object.

4. Content

var myObject = {  A:2 }; myobject.a; // 2 myobject[' a ']; // 2

If you want to access the value of a position in MyObject, we need to use the. operator, or the [] operator

. A syntax is often referred to as property access, and [' a '] syntax is often referred to as key access

The difference is that the. operator requires that the property name satisfy the naming specification of the identifier, while [...] Syntax can accept any Utf-8/unicode string as a property name

Because of the [..] Syntax uses strings to access properties, so you can construct strings in your program

The property name is always a string in an object

5. Computable attribute Name

ES6 adds a computable attribute name, which can be used as a property name in text form using [] wrapping an expression.

var prefix = "foo"var myObject = {  [prefix+ "bar"]: ' Hello ',  [prefix + "Baz"]: ' World ' ; myobject[' Foobar ']; // Hello myobject[' Foobaz ']; //  World

6. Arrays

The array expects a numeric subscript, which means that the value is stored in a non-negative integer

Arrays are also objects, so although each subscript is an integer, you can still add properties to the array

var = [' foo ', MyArray, ' bar '= ' baz '; myarray.length; // 3 Myarray.baz; // ' Baz '

You can see that the length value of the array has not changed, although named properties have been added

If you try to add a property to an array but the property name looks like a number, it becomes a numeric subscript

var = [' foo ', MyArray, ' Bar '];myarray[' 3 '] = ' baz '; myarray.length; // 4myarray[3]; // ' Baz '

7. Copying objects

For JSON-safe objects, there is an ingenious way to replicate:

JSON security: That is, it can be serialized as a JSON string and can parse out an object of exactly the same structure and value based on the string.

var newObj = Json.parse (Json.stringfy (someobj));

This method needs to ensure that the object is JSON-safe, so it is only applicable in some cases

Shallow copy easy to understand, less problems.

Object.assign (..) The first parameter is the target object, which can then be followed by one or more source objects

8. Attribute descriptors

Starting with ES5, all properties have a property descriptor

var myObject = {  A:2}object.getownpropertydescriptor (myObject,' a ');

// {
Value:2,
Writable:true,
Enumerable:true,
Configurable:true
// }

You can use Object.defineproperty () to add a new property, or modify an existing property

Object.defineproperty (MyObject, ' a ', {    2,    true,    true ,     true }); myobject.a; // 2

9, the object default [[Put] and [[Get]] operations can control the setting of property values and

In ES5, the getter and setter sections can be used to override the default action, but only on a single property and cannot be applied across the entire object. Getter is a hidden function that is called when a property value is obtained, and a setter is a hidden function that is called when the property is set.

var myObject = {  get a () {    return 2;   = 3; myobject.a; // 2

Since we have only defined a getter, the set operation ignores the assignment operation and does not throw an error when setting the value of a.

Even with a legitimate setter, the getter we define will only return 2. So the set operation has no meaning.

10, the existence of

We can judge whether this property exists in an object without accessing the value of the property

var myObject = {  A:2};( in myObject);   true in MyObject); // false Myobject.hasownproperty (' a '); // truemyobject.hasownproperty (' B '); // false

The in operator checks whether the property is on the object and its [[Prototype]] prototype chain, in contrast, hasownproperty () checks whether the property is in the MyObject object and does not check the [[Prototype]] Chain

Note: In is actually checking for the existence of a property. For arrays: 4 in [2,4,6] is not true because [2,4,6] contains the property name 0,1,2 No 4

11. Enumeration

An enumerable is equivalent to a traversal that can appear in an object's properties

Does not affect the existence of

For...in ... This enumeration will contain not only all numeric indexes but also all enumerable properties

You don't know the JS-object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.