Explain the attributes and features in JavaScript _javascript tips

Source: Internet
Author: User

The attributes and attributes in JavaScript are two completely different concepts, and I'm going to take a closer look at the attributes and attributes in JavaScript from what I've learned.

The main contents are as follows:

    • Understand the nature of objects in JavaScript, the relationships between objects and classes, the relationship between objects and reference types
    • How object properties are categorized
    • Understanding of attributes in properties

Part One: Understanding the nature of objects in JavaScript, the relationships between objects and classes, and the relationship between objects and reference types

The essence of an object: ECMA-262 defines an object as a collection of unordered attributes, whose properties can contain basic values, objects, or functions. That is, an object is a set of values that have no specific order, and each property or method of an object has a name, which is mapped to a value. So the essence of an object is a hash table: a set of name-value pairs in which the value can be a data or function.

The relationship between objects and classes: In JavaScript, objects and classes have no relationship. This is because there is no concept of a class in ECMAScript, and its objects are different from objects in other classes based languages.

Relationship between object and reference type: object and reference type are not equivalent because each object is created based on a reference type.

Part Two: How object attributes are categorized

An object created by a constructor or object literal method has properties and methods (as long as the properties and methods are mentioned, they must be objects, as long as the object is mentioned, it must have attributes and methods (except customizations), where the attributes can be divided into data and accessor properties, and they differ as follows:

Data properties are typically used to store data values, and accessor properties do not contain a data value

Accessor properties are used more than get/set operations

Part III: Understanding of Attributes in attribute

ECMAScript defines the concept of attributes (attribute) in order to describe various characteristics of object attributes. This means that the attribute is different from the attribute, which is to describe the attribute. Below, I will explain separately:

    • Data attributes and their characteristics
    • accessor properties and their attributes
    • How to define multiple attributes using the Object.defineproperties () method
    • How to use the Object.getownpropertydescripter () method to read a property's descriptor to read attribute attributes

1. Data properties and their characteristics

As we have just said, data attributes are used to store data values, so the data attribute has a position of data value where the value can be read and written. The data attribute has 4 attributes that describe its behavior, because ECMAScript rules: You cannot access attributes directly in JavaScript (note: not inaccessible), so we put it in two sets of square brackets. As follows:

    • [[Configurable]]: The default value is True,a, whether the attribute can be deleted by Delete to redefine property B, whether to modify attributes of the property C, the ability to modify properties from data properties to accessor properties
    • [[Enumerable]]: The default value is true to indicate whether the property can be returned through a for-in loop (so: If False, then the for-in loop cannot enumerate its properties)
    • [[Writable]]: The default value is True, indicating whether the value of the property can be modified, which is different from [[configurable]].
    • [[Value]]: The default value is undefined, which is the property value of the attribute, where we can read the property value or write the property value at that location.
    • Note: The default above is the property owned by the object created by the constructor or object literal, rather than the Object.defineproperty () method described below

These attributes all have default values, but what if these defaults are not what we want? Of course it's a change! We can modify the property default attribute by Object.defineproperty () method. English Difineproperty is the meaning of defining attributes. This method receives three parameters: the object in which the property is located, the name of the property, and a descriptor object. The third parameter descriptor object is created by the method of the object literal, where the property and property values actually hold the attribute and attribute values to be modified.

Here are a few examples to get a deeper understanding.

A

var person={};
Object.defineproperty (person, "name", {
  writable:false,
  value: "Zhuzhenwei"
});
Console.log (person.name);//zhuzhenwei
person.name= "heting";
Console.log (person.name);//zhuzhenwei

Here I created an object using the object literal method, but did not create both methods and properties. Instead, the Object.defineproperty () method was used to create the property and modify the default value. This sets the writable to false, so that when I try to modify the Person.name, it is invalid.

B

var person={};
Object.defineproperty (person, "name", {
  value: "Zhuzhenwei"
});
Console.log (person.name);//zhuzhenwei
person.name= "heting";
Console.log (person.name);//zhuzhenwei

Take a look at this example, in this example I deleted the writable:false, why still can't modify it? That's because before I introduced the features, the first three defaults to Ture, which were created with the creation of objects and the creation of attributes. For properties created by calling the Object.defineproperty () method, the default values for the first three attributes are false, and here you need attention.

C

var person={};
Object.defineproperty (person, "name", {
  value: "Zhuzhenwei",
  configurable:false
});
Console.log (person.name);//zhuzhenwei
delete person.name;
Console.log (person.name);//zhuzhenwei

Here we set the attributes of the newly created property name to Configurable:false, so the following deletion of the property is invalid. According to B, know configurable, the default is false, even if removed can not be modified.

D

var person={};
Object.defineproperty (person, "name", {
  value: "Zhuzhenwei",
  configurable:true
});
Console.log (person.name);//zhuzhenwei
delete person.name;
Console.log (person.name);//undefined

Here I changed the default configurable value from the default of false to True, so it became configurable, and then it was successfully deleted.

E

var person={};
Object.defineproperty (person, "name", {
  value: "Zhuzhenwei",
  configurable:false
});
Console.log (person.name);//zhuzhenwei
object.defineproperty (person, "name", {
  value: "Zhuzhenwei",
  Configurable:true
});
Console.log (person.name);//uncaught Typeerror:cannot redefine property:name (...)

If it has previously been set to false, then it is futile to change it back to true, that is, once the property is set to be not configurable, it cannot be changed back to configurable.

F

Console.log (person.name);//uncaught Typeerror:cannot redefine Property:name (...)
var person={};
Object.defineproperty (person, "name", {
  value: "Zhuzhenwei",
});
Console.log (person.name);//zhuzhenwei
object.defineproperty (person, "name", {
  value: "Zhuzhenwei",
  configurable:true
});
Console.log (person.name);//uncaught Typeerror:cannot redefine property:name (...)

This shows that even if the previous step we do not ignore the default Configurable:false, the following is still not configurable. As a result, it can be concluded that, in order to be configurable, the default value must be modified to true the first time the Object.defineproperty () function is invoked.

2. Accessor properties and their characteristics 

As mentioned earlier, accessor properties do not contain data values, they contain a pair of getter functions and setter functions (these two functions are not required). When the accessor property is read, the Getter function is called, which is responsible for returning a valid value, and when the write accessor property is, the setter function is invoked and the new value is passed in, which is responsible for deciding how to process the data. Similarly, because the attributes of accessor properties cannot be accessed directly through JavaScript, the attributes listed below will be divided by [[]].

    • [[Configurable]]: The default value is True,a, which indicates whether the property can be deleted by deleting it, thereby redefining property B, modifying attributes of attribute C, being able to modify properties from accessor properties to data properties
    • [[Enumerable]]: The default value is true to indicate whether the property can be returned through a for-in loop (so: If False, then the for-in loop cannot enumerate its properties)
    • [[Get]]: The function that is called when the property is read . The default value is undefined key: The attribute can be a function
    • [[Set]]: The function that is called when the property is written . The default value is undefined key: An attribute can be a function because the get and set functions also belong to attributes, It is possible, then, that they (possibly because these two functions are not necessary) appear in the properties of the third parameter descriptor object of Object.defineproperty.

Note: 1. Relative to the data attribute, we find that there is no writable attribute and value attribute in accessor properties. This is because accessor properties do not contain data values, so of course we cannot modify the value of the property (not using the writable attribute), let alone value.

2. accessor properties cannot be directly defined and must be defined with Object.defineproperty () . (This allows us to accurately determine accessor properties and data properties)

Take the following example to get a deeper understanding:

var book={
  _year:2004,
  edition:1
};
Object.defineproperty (book, ' Year ', {
  get:function () {<br> return this._year;
  },
  set:function (NE Wvalue) {
    if (newvalue>2004) {
      this._year=newvalue;
      this.edition+=newvalue-2004
    }}
);
book.year=2005;
Console.log (book.edition);//2

A few areas that require deep understanding:

    • Accessor properties cannot be defined directly, must be defined using Object.defineproperty (), and the property has set and GER attributes, so it is possible to judge that _year and edition are data properties, and year is accessor properties.
    • We see _year This data attribute preceded by _ (underscore), a commonly used notation that represents a property that can only be accessed through an object method. From the example above you can see a method that is equivalent to a Descriptor object, and _year is exactly the property that is accessed in this object method. Edition can be accessed either through object methods or directly by objects.
    • Book.year indicates that the accessor property is being read , the Get function is called, and the valid value of 2004 is returned.
    • BOOK.YEAR=2005 represents the write accessor property , the Set function is called and the new value is passed in, and the 2005 is passed to NewValue, which determines how the data is processed.
    • The common way to use accessor properties is to set the value of one property to cause other properties to change.

3. How to define multiple attributes using the Object.defineproperties () method

Obviously, an object cannot have only one attribute, so there is a high likelihood of defining multiple attributes, so JavaScript provides a object.defineproperties () method to solve the problem. This method receives two parameters, the first is to define the object in which the property is located, and the second is an object that is created by an object literal method, whose property name is the special name to be defined, and an object whose property name and attribute value are respectively attribute names and attribute values. (This is not very well understood, see examples).

var book={};
Object.defineproperties (book,{
  _year:{
    writable:true,
    value:2004
  },
  edition:{
    writable : True,
    value:1
  },
  year:{
    get:function () {return
      this._year;
    },
    set:function () {
      if (newvalue>2004) {
        this._year=newvalue;
        this.edition+=newvalue-2004
      }}
    }
);

4. How to use the Object.getownpropertydescripter () method to read attribute descriptors to read attribute attributes

We can use the Object.getownpropertydescripter () method to obtain a descriptor for the given property. Getownpropertydescripter is to obtain the meaning of its own attribute descriptor. This method receives two parameters: the object in which the property is to read the property name of its descriptor. Returns an object.

For accessor properties, the object's properties are configurable, enumerable, get, and set;

For data properties, the properties of this object are configurable, enumerable, writable, and value.

var book={};
Object.defineproperties (book,{
  _year:{
    value:2004
  },
  edition:{
    value:1
  },
  year:{
    Get:function () {return
      this._year;
    },
    set:function () {
      if (newvalue>2004) {
        this._year =newvalue;
        this.edition+=newvalue-2004
      }}
    }
);
var descriptor=object.getownpropertydescriptor (book, "_year");
Console.log (descriptor.value);//2004
Console.log (descriptor.configurable);//false Because the attributes of the property created by the Object.defineproperties () method configurable enumerable are false
Console.log (typeof Descriptor.get); Undefined Note: This is a data attribute, a
var descriptor=object.getownpropertydescriptor (book, "Year") that does not have a get feature;
Console.log (descriptor.value);//undefined
Console.log (descriptor.enumerable);//false
Console.log ( typeof Descriptor.get);//function get is an attribute of a property, but it is also a function.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!

Related Article

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.