Object objects in JavaScript

Source: Internet
Author: User
Tags list of attributes object object hasownproperty

Object is a type that we use frequently in JavaScript, and all of the objects in JS are inherited from object objects. Although we usually simply use object object to store the data, and do not use too many other functions, but the object objects actually contain many useful properties and methods, especially the ES5 increment method, so this article will start from the most basic introduction, The common methods and applications of object are described in detail.

Back to top basics about creating objects

First of all we know that an object is a set of similar data and functions that we use to simulate objects in our real world. In JavaScript, there are usually two ways to create objects: constructors and object literals.

New constructor method
1 var person = new Object (); 2 person.name = "Wolf Wolf fat"; 3 person.age = 25;

This method uses the new keyword, followed by the object constructor, and then dynamically adds different properties to the object instance. This approach is relatively cumbersome, and it is generally recommended to use object literals to create objects.

Object literal

The object literal is well understood, and it is simple and convenient to create objects directly using the Key/value form.

1 var person = {2     name: "Wolf Wolf's Blue Fat", 3     age:254};

This way, the object's properties are wrapped directly through curly braces, and object properties are created using Key/value, separated by commas.
Note: If this is the last attribute, then do not add a comma, because in some old browsers will be error.

Properties and methods for object instances

Regardless of the way the object instance is created, the instance will have the following properties and methods, as described below.

Constructor property

The constructor property is the constructor that holds the current object, and in the previous example, constructor saves the object method.

1 var obj1 = new Object (), 2 obj1.id = "Obj1", 3 var obj2 = {4     "id": "obj2" 5};6 7 Console.log (obj1.constructor);//funct Ion Object () {}8 console.log (obj2.constructor);//function object () {}
hasOwnProperty (PropertyName) method

The hasOwnProperty method receives a string parameter that represents the property name, which is used to determine whether the property is in the current object instance, rather than in the prototype chain of the object. Let's take a look at the following example:

1 var arr = [];        2 Console.log (Arr.hasownproperty ("Length")),//true3 Console.log (Arr.hasownproperty ("hasOwnProperty"));//false

In this example, by defining an instance of an array object arr, we know that the array object actually inherits the object from the prototype chain and then has some of its own properties, and we use the hasOwnProperty method to determine that length is the property of Arr itself, And hasOwnProperty is the attribute on the prototype chain.
The hasOwnProperty method can be used with the for: In combines to get the object's own key.

isPrototypeOf (Object) method

The Isprototype method receives an object that is used to determine whether the current object is on the prototype chain of an incoming parameter object, which is somewhat abstract, and we look at the code.

1 function MyObject () {}2 var obj = new MyObject (); 3 Console.log (Object.prototype.isPrototypeOf (obj));

We know that MyObject is inherited from object, and in JS, inheritance is implemented by prototype, so the prototype of object must be on the prototype chain of the MyObject object instance.

propertyIsEnumerable (Prototypename) method

The prototypeisenumerable is used to determine whether a given property can be a for. In statement to enumerate out. Look at the following code:

1 var obj = {2     name: "objname" 3}  4 for (var i in obj) {5     console.log (i); 6}

Executing this code output string "name", which means that the for...in statement can get the name of obj property, but we know that there are many properties of obj, such as constructor, such as Hasownprototype, etc., but they are not output , which means that these properties cannot be enumerated by for...in and can be obtained by means of the propertyIsEnumerable method.

1 Console.log (Obj.propertyisenumerable ("constructor"));//false

Determine if "constructor" can be enumerated, and the output false indicates that it cannot be enumerated.

toLocaleString () method

The Tolocalstring method returns the string representation of an object, which is related to the execution environment of the code.

1 var obj = {};2 Console.log (obj.tolocalestring ());//[object Object]  3 4 var date = new Date (); 5 Console.log (Date.tolo Calestring ());//2016/2/28 1:39:27
ToString () method

The string representation that ToString uses to return an object.

1 var obj = {};2 Console.log (obj.tostring ()),//[object object]3 4 var date = new Date (), 5 Console.log (date.tostring ());//s Un Feb 13:40:36 gmt+0800 (China Standard Time)
ValueOf () method

The ValueOf method returns the original value of the object, possibly a string, numeric, or bool value, to look at the specific object.

1 var obj = {2     name: "obj" 3}; 4 Console.log (Obj.valueof ());//object {name: "obj"} 5  6 var arr = [1]; 7 console. Log (arr.valueof ());//[1] 8  9 var date = new Date (); Console.log (date.valueof ());//1456638436303

As the code shows, three different object instances call valueof to return different data.

Types of properties

In JavaScript, there are two types of attributes, data properties and accessor properties, and let's look at what these two properties are specifically.

Data properties

Data properties We can understand the properties that we assign when we define an object, which can be read and written. However, ES5 defines features that are used to describe the various characteristics of an attribute, which is an intrinsic value and cannot be accessed directly. The attribute is represented by two opposing brackets, such as [[Enumerable]]. Property will have some default values, to modify the default value of the attribute, you must modify it using the new method Object.defineproperty method defined by ES5.
The data attribute has 4 attributes that describe its characteristics, and each of these features is described in turn:
(1) [[[Configurable]]: This attribute indicates whether a property can be deleted by using the delete operator, and the default value is true.

1 var obj = {};2 Obj.name = "MyName"; 3 4 Delete obj.name;5 console.log (obj.name);//undefined

This code is obviously, after deleting the Name property of obj with delete, we can not access the Name property again.
We use the Object.defineproperty method to modify [[Configurable]] properties.

1 var obj = {};2 Obj.name = "MyName"; 3 Object.defineproperty (obj, "name", {4     configurable:false5})                6 7 Delete ob J.name;8 Console.log (obj.name);//myname

By setting the configurable attribute to false, delete cannot delete the Name property, and if you use delete in strict mode, you will get an error.

(2) [[[Enumerable]]: Indicates whether the property can be enumerated by the for...in statement, the default is True
Let's take a look at the previous example:

1 var obj = {2     name: "objname" 3}  4 for (var i in obj) {5     console.log (i);//name6}

This code only outputs the Name property, let's set the [[Enumerable]] of the constructor property to true and try it.

1 var obj = {2         name: "ObjName" 3} 4 Object.defineproperty (obj, "constructor", {5     enumerable:true 6}) 7  8 for (var i in obj) {9     console.log (i);//name,constructor10}11 Console.log (obj.propertyisenumerable ("constructor") );//true

In this code, the for...in loop obtains the name and constructor two properties, and the propertyIsEnumerable method is used to determine that constructor also returns true.

(3) [[[Writable]]: Indicates whether the property value can be modified, the default is True
if [[writable]] is set to false, there will be no effect when trying to modify, error in strict mode

(4) [[value]]: Represents the value of the property, default is undefined

Let's look at these two features in a simple example:

1 var obj = {2     name: "Name" 3}; 4 Console.log (obj.name);//name         5  6 object.defineproperty (obj, "name", {7
   value: "NewValue", 8     writable:false 9}) Console.log (obj.name);//newvalue11 obj.name = "OldValue"; Log (obj.name);//newvalue

We first defined the Name property value of the Obj object as "name" and then modified the value by the DefineProperty method and set it to non-modifiable. We then modify the value of the Name property to find that the modification is invalid.
If we modify the value of the Name property through DefineProperty, can we modify it? The answer is yes:

1 object.defineproperty (obj, "name", {2     value: "OldValue" 3}) 4 Console.log (obj.name);//oldvalue
Accessor properties

Accessor properties are somewhat similar to properties in C #, and the difference between data properties is that it does not have the [[writable] and [[Value]] Two attributes of the data property, but rather has a pair of getter and setter functions.
[[Get]]: function Called when reading properties, default is undefined
[[Set]]: function called when setting property, default is undefined
Getter and setter is a useful thing, assuming there are two properties, where the second property value changes with the first property value. This scenario is very common in our usual coding. In the previous practice, we tended to manually modify the value of the second property, and now we can solve the problem with the get and set functions. Look at the following example:

1 var person = {2     age:10 3} 4  5 object.defineproperty (person, "type", {6     get:function () {7         if (pers On.age >) {8             return "adult", 9         }10         return "child", one     }12}) Console.log (person.type);//Child Perso N.age = 18;17 Console.log (person.type);//Adult

By modifying the value of age, the value of type is modified accordingly so that we do not have to manually modify the value of type.
The same effect can be achieved in the following way:

1 var person = {2     _age:10, 3     type: ' Child ' 4}  5  6 object.defineproperty (person, ' age ', {7     get:functi On () {8         return this._age; 9     },10     set:function (newvalue) {one         this._age = newvalue;12         This.type = NE Wvalue > 17? "Adult": "Child";     }14}) Console.log (person.type); person.age = 18;18 Console.log (person.type);

There are a few things to note about accessor properties:
1, Strict mode, you must set both get and set
2, non-strict mode, you can set only one, if only get, the property is read-only, if set only, the property cannot read
3, Object.defineproperty is a new method in the ES5, IE9 (IE8 partial implementation, only the DOM object is supported) the following browsers do not support, some old browsers can pass non-standard method Definegetter() and Definesetter () to set up, there is no explanation, interested students can find relevant information.

Related methods for attribute operations

ES5 provides some methods for reading or manipulating attribute properties, and the Object.defineproperty used earlier is one of them. I have summed up some of the more commonly used methods as follows:

(1) Object.defineproperty
Defines the properties of an object, which we have used many times before, simply speaking its usage.

1 Object.defineproperty (Obj,propname,descriptor);

DefineProperty is somewhat similar to a static method that is fixed on an object, which is called directly through an object, and it receives 3 parameters:
OBJ: An object that needs to define a property
Propnane: Name of the attribute that needs to be defined
DefineProperty: Property descriptor, which contains attribute definitions for some properties
Examples are as follows:

1 var obj = {};2 Object.defineproperty (obj, "name", {3     value: "Name", 4     configurable:true,5     writable:true,6     Enumerable:true7});

(2) Object.defineproperties
Similar to DefineProperty, is used to define object properties, but it can be used to define multiple properties at the same time, as we can see by naming, using the following:

1 var obj = {}; 2 Object.defineproperty (obj, {3     "name": {4         value: "Name", 5         configurable:true, 6         writable:true, 7
   enumerable:true 8     }, 9     "age": {         value:20-     }12});

(3) Object.getownpropertydescriptor
ES5 also provides a way to read the value of an attribute, which receives an object and its property as two parameters, returning an object that contains different values depending on the type of the property.

1 var person = {2     _age:10, 3     type: ' Child ' 4} 5 object.defineproperty (person, ' age ', {6     get:function () {7< C4/>return This._age; 8     }, 9     set:function (newvalue) {         this._age = newvalue;11         this.type = newvalue > 17? "Adult": "Child";     }13}) Console.log (Object.getownpropertydescriptor (person, "type")),//object {value: "adult", Writable:true, Enumerable:true, configurable:true}16 console.log (Object.getownpropertydescriptor (person, "age")); Object {enumerable:false, Configurable:false, Get:function (), Set:function ()}
method to return to the top of the object

In ES5, a new batch of methods are added to object objects, which can be accessed directly through object, and the previous defineproperty is one of the new methods. In addition, there are many ways, I will summarize the following:

Object-Creation Method Object.create (proto, [Propertiesobject])

As we mentioned before, there are two ways to create an object: Constructors and object literals.
One drawback of both approaches is that if you're creating multiple objects, it's tedious to write, so there's a way to create a custom constructor to create the object as follows:

1 function person (name, age) {2     this.name = name;3     this.age = age;4}5 6 var person = new Person ("Jack", 15);

This method can be very convenient to create many of the same objects, but also the most commonly used methods.

The Object.create method provided by ES5 is also a method of creating objects that allows you to select a prototype object for the created object, without having to define a constructor. Use the following:

1 var obj = object.create (Object.prototype, {2     name: {3         value: "Jack" 4     }5}) 6 Console.log (obj.name);//jack

The first parameter received by this method is the prototype of the object being created, and the second parameter is the property of the object. Note: In this example, the Name property cannot be modified because it does not have the writable attribute set and the default is False.
Personal Opinion: Object.create This creates an object in a slightly cumbersome way, except that it is not recommended to create an object in this way unless it is an attribute that needs to be modified.

Property-Acquisition Method Object.keys

Object.keys is the property name used to get all enumerable properties of the given object, which returns an array.

1 function Parent () {2     this.lastname = "Black" 3} 4 function Child (firstName) {5     this.firstname = firstName; 6 } 7 Child.prototype = new Parent (); 8  9 var son = new Child ("Jack"), Console.log (Object.keys (son));//["FirstName"]

FirstName is returned in the code and does not return LastName and non-enumerable related properties inherited from prototype.
In some old browsers, we can use hasOwnProperty and for...in to achieve similar results.

1 Object.keys = Object.keys | | 2     function (obj) {3         var keys = []; 4 for         (var key in obj) {5             if (Obj.hasownproperty (key)) {6                 keys. Push (key); 7             } 8         } 9         return keys;10     }
Object.getownpropertynames ()

Getownpropertynames is used to get all the properties of the object itself, including all enumerable and non-enumerable properties, as follows:

1 function Parent () {2     this.lastname = "Black" 3} 4 function Child (firstName) {5     this.firstname = firstName; 6 } 7 Child.prototype = new Parent (); 8  9 var son = new Child ("Jack"), Object.defineproperty (son, ' age ', {     enumerable:false12}) Console.log (OBJ Ect.keys (son));//["FirstName"]  console.log (Object.getownpropertynames (son));//["FirstName", "age"]

We define a non-enumerable attribute of age for the son object, and then get the list of attributes through the keys and Getownpropertynames two methods, which clearly shows the difference.

Attribute attribute type method

This is primarily the three methods mentioned earlier: Defineproperty,defineproperties and Getownpropertydescriptor three methods

Object-Constrained methods

ES5 provides a set of methods that restrict the modification of objects to prevent errors caused by inadvertent modification of certain objects. Each restriction type contains a judgment method and a setup method.

Block Object extension

Object.preventextensions () is used to restrict the extension of an object, and after it is set, the object cannot add new properties, as follows:

1 object.preventextensions (obj);

The method receives an object to be set to be unable to expand as a parameter, note two points:
1. Object properties are not available for extension, but existing properties can be deleted
2. The inability to add a new property refers to the inability to add a property on itself, or to add a property if it is on the object's prototype.

1 function person (name) {2     this.name = name, 3} 4 var person = new Person ("Jack"), 5 object.preventextensions (person ); 6  7 Delete person.name; 8 Console.log (person.name);//undefined 9 Person.prototype.age = 15;11 Console.log ( Person.age);//15

The Object.isextensible method is used to determine whether an object is extensible, by default it is True

Seal the object

Object.seal can seal an object and return the sealed object.
Sealed objects cannot add or remove existing properties or modify the properties ' enumerable,writable,configurable, but you can modify the property values.

1 function person (name) {2     this.name = name;3}4 var person = new Person ("Jack"), 5 object.seal (person), 6 delete person . Name;7 Console.log (person.name);//jack

After the object is sealed, use Delete to delete the object properties, or you can access the resulting property.

The object.issealed can be used to determine whether an object is sealed.

Freeze objects

The Object.freeze method is used to freeze an object, the frozen object cannot be added, modified, deleted, or the attribute value cannot be modified, that is, the object cannot be modified.

1 function person (name) {2     this.name = name, 3} 4 var person = new Person ("Jack"), 5 object.freeze (person); 6  7 Delete Person.name; 8 Console.log (Person.name),//jack 9 Person.prototype.age = 15;11 Console.log (person.age);//15

Analyzing the above code we can see that the frozen object cannot delete its own properties, but it can still add properties through its prototype object.

Object.isfrozen can be used to determine whether an object has been frozen.

It can be found that the limit of the three methods of restricting objects is ascending in turn.

Back to top of the summary

Object is one of the most commonly used objects in our development, but many of its features have not been excavated by us. This paper first introduces the basic use of object, then introduces some of the less used attribute properties, and finally analyzes some common methods, especially the new method provided in ES5. Welcome everyone to Exchange!!

This article address: http://luopq.com/2016/02/28/Object-in-Javascript/, reprint please specify

Object objects in JavaScript

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.