The mystery of JavaScript's Object.defineproperty

Source: Internet
Author: User
Tags define get

Straight Cut Theme

Today we have a feature like this:

    • Write a function that passes two parameters, the first parameter is the total amount of data returned by the object, and the second parameter is the data of the initialized object. Such as:
var o = obj (4, {name: ' Xu ', age:21})   //   Returns an object that can hold 4 data, the initial data is name: ' Xu ' and age:21
    • The returned object always has the following properties: Overlength (Data capacity), size (current number of data bars)
    • The returned object should have the following methods: Cache (save a piece of data), delete (delete a piece of data)
    • Each time a property is referenced, the property value disappears. Such as:
// Xu // undefined // 1

So the question is, how do you set properties to be automatically eliminated after use once, after thinking, think, get and set methods, get and set what is it, as follows:

var o = {  one,  get ID () {    returnthis. _id + ' _get '  },< C10/>set ID (value) {    this. _id = value + ' _set '  }}console.log (o.id)  //  11_geto.id = ' 666 'console.log (o.id)  //  666_set_get

The value of the reference property in JS is treated as a get, and the attribute assignment is treated as a set,get and set method that can perform certain actions when getting/setting the property value.

The Get and set methods are used in this article, but it is not as simple as the above example to write in the object, we use the protagonist Object.defineproperty method of this article.

What is Object.defineproperty

Object.defineproperty is a new way to set the descriptor for an object property in Es5, using the following method:

Object.defineproperty (obj, prop, descriptor)  //  object, property, descriptor

There are 3 basic descriptors:

    • Writable--whether it is writable
    • Configurable--whether it is a configurable
    • Enumerable--whether it is an enumerable

Here is a simple example to illustrate its usage

Writable

As the name implies, sets whether the property is writable and, if false, the assignment operation after the property is invalid

var o = {  ' xu '' name ', {  writeable:false= ' Lee ' Console.log (o.name)   // Xu
Configurable

property is configurable and set to false, the property cannot be deleted or can be changed to configurable, but can be changed from writable to non-writable

var o = {  ' xu '' name ', {  configurable:false= ' Lee '  Console.log (o.name)  //  Lee   cannot configure writable Delete  o.nameconsole.log ( O.name)  //Lee  Delete failed object.defineproperty (o, ' name ', {    False= ' li 'console.log (o.name)  //  Lee  is not configurable and not writable
Enumerable

property is enumerable, if false, the property is not enumerable, and non-enumerable properties are not visible to the for ... in statement and Ojbect.keys.

var o = {  ' Xu ',  ' name ', {  false/ /["Age"]

Dividing line----------------------------------------------------------------------------

In addition to the above three properties, the DefineProperty method can also define the value of the property, the Get/set method, and this chapter uses the Get/set value that defines the property using the Object.defineproperty method.

Answer questions

Idea: The main subject around the get/set of the property to do further processing, the requirement to reference the property value after the property value disappears (undefined), then we need to make a fuss in the Get method, so we first develop a method to define the property descriptor, I define it as:

var_defineproperty =function(ret, key) {Object.defineproperty (ret, key, {set:function(value) {//Set method for O.key = value        if(!Datas[key]) {Ret.size++} Datas[key]=value}, get:function () {        //gets the current data, returns a value if the current data has a value, and sets the current property value to undefined        varres =undefinedif(typeofDatas[key]!==undefined) {Res=Datas[key] Ret.size--Datas[key]=undefined}returnRes}}) }

The main part of the topic is here, this code takes advantage of the properties of the Get and set method, in response to the requirements of the problem, made this function. Note: The returned object RET does not save the data, and he simply sets and reads the data in the Datas cache object through the set and get methods.

Datas object is this, he used the ES6 in the Object.assign method, the init copied a copy for initialization

//   Cache Data  var datas = Object.assign ({}, init)

The entire code is here, also very simple, writing is also quite chaotic. If there is a problem, please indicate.

functionFirstvaild (overlength, init) {//defines the final return object, initial two values, an object's total capacity, and a current length  varRET ={overlength:overlength, size:Math.min (Object.keys (init). Length, Overlength)//if the number of incoming initial data bars is greater than capacity, the capacity value  }  //Cache Data  varDatas =object.assign ({}, init)//functions that define properties  var_defineproperty =function(ret, key) {Object.defineproperty (ret, key, {set:function(value) {//Set method for O.key = value        if(!Datas[key]) {Ret.size++} Datas[key]=value}, get:function () {        //gets the current data, returns a value if the current data has a value, and sets the current property value to undefined        varres =undefinedif(typeofDatas[key]!==undefined) {Res=Datas[key] Ret.size--Datas[key]=undefined}returnRes}}) }  //initialize dirty to false and define get/set for each propertyObject.keys (init). Slice (0,ret.size). Map (function(key) {_defineproperty (ret, key)}) Object.assign (ret, {cache:function(key, value) {if( This. Size >= This. Overlength) {        Throw' Memory is full, please expand capacity '      }      //The attribute does not exist, defines him, and the length +1, the attribute exists but the value does not exist, the length is +1,      if(! (Keyinchdatas)) {_defineproperty ( This, key) This. size++      } Else if(!Datas[key]) {         This. size++      }      //Regardless, the new value overrides the old valueDatas[key] =valuereturn  This    },    //Delete Attribute set the property in Datas to undefined directly    Delete:function(key) {Datas[key]=undefined This. size--return  This    }  })  returnret}

This chapter is here, Bo Master for a front-end novice, and do not have much knowledge, try my best, write a basic knowledge, share to the new people who are learning the front.

The mystery of JavaScript's Object.defineproperty

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.