A detailed explanation of the object _javascript techniques in JavaScript

Source: Internet
Author: User
Tags numeric value object object hasownproperty

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

Basic introduction

Creating objects

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

New constructor Function method

var person = new Object ();
Person.name = "Wolf Wolf's Blue Fat";
Person.age = 25;

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

Object literal Amount

Object literal is very well understood, using the form of Key/value to create objects directly, simple and convenient.

var person = {
  name: "Wolf Wolf's Blue Fat",
  age:25
};

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

Properties and methods of object instances

Regardless of the way you create an object instance, the instance has the following properties and methods, which are described here.

Constructor property

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

var obj1 = new Object ();
Obj1.id = "Obj1";
var obj2 = {
  "id": "Obj2"
};
 
Console.log (obj1.constructor);//function object () {}
Console.log (obj2.constructor);//function object () {}

hasOwnProperty (PropertyName) method

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

var arr = [];    
Console.log (Arr.hasownproperty ("Length"));//true
Console.log (Arr.hasownproperty ("hasOwnProperty")); False

In this example, first by defining an instance of an array object arr, we know that the array object actually inherits the object through the prototype chain, and then owns some of its own properties, and we judge length by the hasOwnProperty method as arr own property, And hasOwnProperty is the attribute on the prototype chain.
The hasOwnProperty method can be used with the for. In combination 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 the incoming parameter object, which is somewhat abstract, let's look at the code.

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

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

propertyIsEnumerable (Prototypename) method

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

var obj = {
name: ' objname '
} for 
(var i in obj) {
console.log (i);
}

This code output string "name" is executed, which means that the attribute of obj's name can be obtained through the for...in statement, but we know that there are many attributes of obj, such as constructor, such as Hasownprototype, but they are not output , which indicates that these attributes cannot be enumerated by for...in and can be obtained by propertyisenumerable method.

Copy Code code as follows:

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

To determine if "constructor" can be enumerated, the output false description cannot be enumerated.

toLocaleString () method

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

var obj = {};
Console.log (Obj.tolocalestring ());//[object Object] 

var date = new Date ();
Console.log (Date.tolocalestring ());//2016/2/28 1:39:27

ToString () method

The string representation that ToString uses to return an object.

var obj = {};
Console.log (Obj.tostring ());//[object Object]
    
var date = new Date ();
Console.log (Date.tostring ())//sun Feb 2016 13:40:36 gmt+0800 (China Standard Time)

ValueOf () method

The ValueOf method returns the original value of the object, possibly a string, a numeric value, or a bool value, and so on, to see the specific object.

var obj = {
  name: ' obj '
};
Console.log (Obj.valueof ());//object {name: "obj"}

var arr = [1];
Console.log (Arr.valueof ());//[1]

var date = new Date ();
Console.log (Date.valueof ());//1456638436303

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

Type of property

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

Data properties

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

var obj = {};
Obj.name = "MyName";
    
Delete Obj.name;
Console.log (obj.name);//undefined

This code is obvious, after deleting the name attribute of obj with delete, we can access the Name property again.
We modify the [[configurable]] attribute through the Object.defineproperty method.

var obj = {};
Obj.name = "MyName";
Object.defineproperty (obj, "name", {
  configurable:false
})        

delete obj.name;
Console.log (obj.name);//myname

By setting the configurable attribute to false, delete cannot remove the Name property, and if you use Delete to delete it in strict mode, the error will be made.

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

var obj = {
  name: "objname"
} for 
(var i in obj) {
  console.log (i);//name
}

This code outputs only the Name property, and we will try to set the [[Enumerable]] of the constructor property to true.

var obj = {
    name: "objname"
}
object.defineproperty (obj, "constructor", {
  enumerable:true
}) For

(var i in obj) {
  console.log (i);//name,constructor
}
console.log (Obj.propertyisenumerable ( "constructor"));//true

In this code, the for...in loop gets 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, and an error will be made in strict mode

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

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

var obj = {
  name: ' Name '
};
Console.log (obj.name);//name    

object.defineproperty (obj, "name", {
  value: "NewValue",
  writable:false
})
Console.log (obj.name);//newvalue

obj.name = "OldValue";
Console.log (obj.name);//newvalue

We first defined the Obj object's Name property value as "name", and then modified the value by the DefineProperty method, and set it to not 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 by DefineProperty, can we modify it? The answer is yes:

Object.defineproperty (obj, "name", {
  value: "OldValue"
})
Console.log (obj.name);//oldvalue

Accessor properties

Accessor properties are somewhat analogous to attributes in C #, and the difference between data properties is that it has no two attributes of the data attribute [[writable]] and [[Value]], but rather has a pair of getter and setter functions.
[[Get]]: The function that is called when the property is read, the default is undefined
[[Set]]: The function that is called when the property is set, the default is undefined
Getter and setter are very useful things, assuming there are two properties, where the second property value changes with the first property value. It is very common for this scenario to start in our usual coding. In the previous practice, we tended to manually modify the value of the second attribute, so now we can solve the problem by getting and set functions. Look at the following example:

var person = {
  age:10
}

object.defineproperty (person, ' type ', {
  get:function () {
    if (person.age &G T {return
      "adult";
    }
    return "Child";
  }
)

Console.log (Person.type);//child

person.age =;
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 the type.
The same effect can be achieved in the following way:

var person = {
  _age:10,
  type: "Child"
} 

Object.defineproperty (person, ' age ', {
  get:function () { return
    this._age
  },
  set:function (newvalue) {
    this._age = newvalue;
    This.type = newvalue > 17? "Adult": "Child";
  }
)
Console.log (person.type);

Person.age =;
Console.log (Person.type);

There are a few things to note about accessor properties:
1. In strict mode, get and set must be set at the same time
2, not strict mode, you can set only one, if you set only get, the property is read-only, if set only, the property cannot read
3, Object.defineproperty is a new method in ES5, IE9 (IE8 partial implementation, only the DOM object support) The following browsers do not support, some older browsers can Definegetter () and Definesetter () by nonstandard methods () To set, there is no explanation, interested students can find relevant information.

Related Methods of attribute operation

ES5 provides methods for reading or manipulating attribute attributes, one of which is the Object.defineproperty used earlier. 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 several times before, simply to say its usage.

Copy Code code as follows:

Object.defineproperty (Obj,propname,descriptor);

DefineProperty is somewhat similar to a static method that is fixed on object, called directly by object, which receives 3 parameters:
Obj: Object that needs to define attributes
Propnane: attribute name that needs to be defined
DefineProperty: Property descriptor, containing attribute definitions for some attributes
Examples are as follows:

var obj = {};
Object.defineproperty (obj, "name", {
  value: "Name",
  configurable:true,
  writable:true,
  Enumerable: True
});

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

var obj = {};
Object.defineproperty (obj, {
  "name": {
    Value: "Name",
    configurable:true,
    writable:true
    , Enumerable:true
  },
  "age": {
    value:20 
  }
});

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

var person = {
  _age:10,
  type: "Child"
}
Object.defineproperty (person, ' age ', {
  get:function ()
    { Return This._age
  },
  set:function (newvalue) {
    this._age = newvalue;
    This.type = newvalue > 17? "Adult": "Child";
  }
)

Console.log (Person, "type") Object.getownpropertydescriptor//object {value: adult, writable:true, Enumerable:true, Configurable:true}
Console.log (Object.getownpropertydescriptor (person, ' age '));//object {enumerable:false, Configurable:false, Get:function (), Set:function ()}

Method of Object

In ES5, a new number of methods are added to object objects that can be accessed directly through object, and the DefineProperty used earlier is one of the new methods. There are many other ways to do this, and I'll summarize them as follows:

Object-Creation methods

Object.create (Proto, [Propertiesobject])

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

function person (name, age) {
  this.name = name;
  This.age = age;
}

var person = new Person ("Jack", 15);

This is a convenient way to create many of the same objects, and is currently the most common method.

The Object.create method provided by ES5 is also a method of creating objects, which allows you to select a prototype object for the created object and not to define a constructor. Usage is as follows:

var obj = object.create (object.prototype, { 
  name: {
    value: "Jack"
  }
})
Console.log (obj.name); Jack

This method receives the first parameter as the prototype of the object being created, and the second parameter is the object's property. Note: In this example, the Name property cannot be modified because it does not set the writable attribute, and the default is False.
Personal opinion: Object.create this way of creating objects is a bit cumbersome, and it is not recommended to create objects in this way unless you need to modify the attributes of a property.

Property-Fetching method

Object.keys

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

function Parent () {
  this.lastname = ' black '
}
function Child (firstName) {
  this.firstname = firstname;< c5/>}
child.prototype = new Parent ();

var son = new Child ("Jack");
Console.log (Object.keys (son));//["FirstName"]

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

Object.keys = Object.keys | |
  function (obj) {
    var keys = [];
    for (var key in obj) {
      if (Obj.hasownproperty (key)) {
        Keys.push (key);
      }
    }
    return keys;
  }
Object.getownpropertynames ()

Getownpropertynames is used to get all of the properties of the object itself, including all attributes that can be enumerated and not enumerated, as follows:

function Parent () {
  this.lastname = ' black '
}
function Child (firstName) {
  this.firstname = firstname;< c5/>}
child.prototype = new Parent ();

var son = new Child ("Jack");
Object.defineproperty (son, "age", {
  enumerable:false
})
Console.log (Object.keys (son));//[" FirstName "] 
console.log (Object.getownpropertynames (son))//[" FirstName "," age "]


We define the son object to define an enumerable attribute age, and then get the list of properties by using the keys and getownpropertynames two methods to see the difference clearly.

Attribute attribute type method

This is mainly mentioned in the previous three methods: Defineproperty,defineproperties and Getownpropertydescriptor three methods

Object-Restricted method

ES5 provides a series of methods for restricting the modification of objects to prevent errors caused by unintentional modification of certain objects. Each restriction type contains a judgment method and a setting method.

Block Object Extensions

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

Copy Code code as follows:

Object.preventextensions (obj);

This method receives an object to be set to be unable to be extended as a parameter and requires two points to note:
1, the object's properties are not available for extension, but existing properties can be deleted
2. The inability to add a new property means that the attribute cannot be added to itself, if it is on the object's prototype, or it can be added.

function person (name) {
  this.name = name;
}
var person = new Person ("Jack");
Object.preventextensions (person);

Delete Person.name;
Console.log (person.name);//undefined

Person.prototype.age =;
Console.log (person.age);//15

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

Seal an Object

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

function person (name) {
  this.name = name;
}
var person = new Person ("Jack");
Object.seal (person);
Delete Person.name;
Console.log (person.name);//jack

After you seal the object, use Delete to delete the object properties or access the properties.

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

Freezing objects

The Object.freeze method is used to freeze an object, the frozen object will not be able to add, modify, delete, or modify attribute values, that is, the object cannot be modified.

function person (name) {
  this.name = name;
}
var person = new Person ("Jack");
Object.freeze (person);

Delete Person.name;
Console.log (person.name);//jack

Person.prototype.age =;
Console.log (person.age);//15

Analysis of the above code we can find that the frozen object cannot delete its own properties, but through its prototype object can still add properties.

The Object.isfrozen can be used to determine whether an object is frozen.

As you can see, the limits of the methods of these three restricted objects are ascending in turn.

Summarize

Object is one of the most frequently used objects in our development, but many of its functions have not been excavated by us. This paper first introduced the basic use of object, then introduced some less used attribute characteristics, and finally analyzed some of the more commonly used methods, especially the new method provided in the ES5. Welcome everyone to communicate!!

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

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.