国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial JS adds getter+setter summary

JS adds getter+setter summary

Jun 12, 2018 am 09:36 AM
getter js setter

This time I will bring you a summary of adding getter setters in JS. What are the precautions for adding getter setters in JS? The following is a practical case, let’s take a look.

Define getter and setter<br>

1. Specify it when creating the object through the object initializer (it can also be called declaring when creating the object through literal value)

(function?()?{
??var?o?=?{
????a?:?7,
????get?b(){return?this.a?+1;},//通過?get,set的?b,c方法間接性修改?a?屬性
????set?c(x){this.a?=?x/2}
??};
??console.log(o.a);
??console.log(o.b);
??o.c?=?50;
??console.log(o.a);
})();

The debugging view in chrome is as follows:

JS adds getter+setter summary

You can see that there are more get attributes and set attributes
under the object. The output result is as follows:

JS adds getter+setter summary

Of course the get statement and the set statement can be declared multiple times to correspond to multiple getters and setter<br> The advantage of using this method is that the corresponding getter and setter<br> can be declared at the same time when declaring the attribute. Here Someone asked, can the method names of the get and set methods of the o object be changed to "a", so that the method can be accessed directly through "." and operated directly

(function () {
  var o = {
    a : 7,
    get a(){return this.a +1;},//死循環(huán)
    set a(x){this.a = x/2}
  };
  console.log(o.a);
  console.log(o.b);
  o.c = 50;
  console.log(o.a);
})();

Open chrome to view the creation The view is as follows:

JS adds getter+setter summary

You can see that the get and set methods at this time are different from the above, but do they really work? The answer is no. When we What is called through o.a is the a method declared by the get statement. After entering the method, the this.a method is encountered and the method continues to be called to form an infinite loop, which eventually leads to an infinite loop reporting a memory overflow error.

New syntax (ES6): Currently only supported by firefox, other browsers will report errors

(function () {
  var b = "bb";
  var c = "cc";
  var o = {
    a : 7,
    get [b](){return this.a +1;},
    set [c](x){this.a = x/2},
  };
  console.log(o.a);
  console.log(o[b]);
  o["cc"] = 50;
  console.log(o.a);
})();

Open firefox to view debugging:

JS adds getter+setter summary

Output The result is as follows:

JS adds getter+setter summary

2. Use the Object.create method

Quote MDN:

Overview
The Object.create() method creates an object with the specified prototype and several specified properties.

Syntax
Object.create(proto, [ propertiesObject ])

We all know that when using the Object.create method to pass a parameter, you can create a prototype based on the parameter. A brief talk about the 8 modes of creating objects in JS
The second parameter is optional and is an anonymous parameter object. The parameter object is a set of attributes and values. The attribute name of the object will be the newly created object. The attribute name, the value is the attribute descriptor (including extended data descriptor or access descriptor, see the following content for specific explanation of what an attribute descriptor is).
Through the property descriptor we can add the get method and set method to the newly created object

(function () {
  var o = null;
  o = Object.create(Object.prototype,//指定原型為 Object.prototype
      {
        bar:{
          get :function(){
            return 10;
          },
          set : function (val) {
            console.log("Setting `o.bar` to ",val);
          }
        }
      }//第二個(gè)參數(shù)
    );
  console.log(o.bar);
  o.bar = 12;
})();

The debugging attempt in chrome is as follows:

JS adds getter+setter summary

You can see that newly created objects have more get and set attributes.
The output results are as follows:

JS adds getter+setter summary

The above example is not used for the get method and set method. Attribute

(function () {
  var o = null;
  o = Object.create(Object.prototype,//指定原型為 Object.prototype
      {
        bar:{
          get :function(){
            return this.a;
          },
          set : function (val) {
            console.log("Setting `o.bar` to ",val);
            this.a = val;
          },
          configurable :true
        }
      }//第二個(gè)參數(shù)
    );
  o.a = 10;
  console.log(o.bar);
  o.bar = 12;
  console.log(o.bar);
})();

or:

(function () {
  var o = {a:10};
  o = Object.create(o,//指定原型為 o 這里實(shí)際可以理解為繼承
      {
        bar:{
          get :function(){
            return this.a;
          },
          set : function (val) {
            console.log("Setting `o.bar` to ",val);
            this.a = val;
          },
          configurable :true
        }
      }//第二個(gè)參數(shù)
    );
  console.log(o.bar);
  o.bar = 12;
  console.log(o.bar);
})();

The output result is as follows:

JS adds getter+setter summary

The advantage of using this method is that it is highly configurable, but Beginners can get confused easily.

3. Use the Object.defineProperty method

Quote MDN:

Summary
The Object.defineProperty() method is directly used in a Define a new property on the object, or modify an existing property, and return the object.
Syntax
Object.defineProperty(obj, prop, descriptor)
Parameters
obj
The object whose properties need to be defined.
prop
The property name that needs to be defined or modified.
descriptor
Descriptor of the attribute that needs to be defined or modified.

(function () {
  var o = { a : 1}//聲明一個(gè)對(duì)象,包含一個(gè) a 屬性,值為1
  Object.defineProperty(o,"b",{
    get: function () {
      return this.a;
    },
    set : function (val) {
      this.a = val;
    },
    configurable : true
  });

  console.log(o.b);
  o.b = 2;
  console.log(o.b);
})();

The difference between this method and the previous two is: using the previous two methods, you can only specify getters and setters when declaring the definition. Using this method, you can add or modify them at any time.

If you need to add getters and setters in batches at one time, there is no problem. Use the following method:

4. Use the Object.defineProperties method

MDN:

概述
Object.defineProperties() 方法在一個(gè)對(duì)象上添加或修改一個(gè)或者多個(gè)自有屬性,并返回該對(duì)象。
語法
Object.defineProperties(obj, props)
參數(shù)
obj
將要被添加屬性或修改屬性的對(duì)象
props
該對(duì)象的一個(gè)或多個(gè)鍵值對(duì)定義了將要為對(duì)象添加或修改的屬性的具體配置

不難看出用法與 Object.defineProperty 方法類似

(function () {
  var obj = {a:1,b:"string"};
  Object.defineProperties(obj,{
    "A":{
      get:function(){return this.a+1;},
      set:function(val){this.a = val;}
    },
    "B":{
      get:function(){return this.b+2;},
      set:function(val){this.b = val}
    }
  });

  console.log(obj.A);
  console.log(obj.B);
  obj.A = 3;
  obj.B = "hello";
  console.log(obj.A);
  console.log(obj.B);
})();

輸出結(jié)果如下:

JS adds getter+setter summary

5.使用 Object.prototype.__defineGetter__ 以及 Object.prototype.__defineSetter__ 方法

(function () {
  var o = {a:1};
  o.__defineGetter__("giveMeA", function () {
    return this.a;
  });
  o.__defineSetter__("setMeNew", function (val) {
    this.a = val;
  })
  console.log(o.giveMeA);
  o.setMeNew = 2;
  console.log(o.giveMeA);
})();

輸出結(jié)果為1和2
查看 MDN 有如下說明:

JS adds getter+setter summary

什么是屬性描述符

MDN:

對(duì)象里目前存在的屬性描述符有兩種主要形式:數(shù)據(jù)描述符和存取描述符。

  1. 數(shù)據(jù)描述符是一個(gè)擁有可寫或不可寫值的屬性。

  2. 存取描述符是由一對(duì) getter-setter 函數(shù)功能來描述的屬性。

  3. 描述符必須是兩種形式之一;不能同時(shí)是兩者。

數(shù)據(jù)描述符和存取描述符均具有以下可選鍵值:

configurable
當(dāng)且僅當(dāng)這個(gè)屬性描述符值為 true 時(shí),該屬性可能會(huì)改變,也可能會(huì)被從相應(yīng)的對(duì)象刪除。默認(rèn)為 false。
enumerable
true 當(dāng)且僅當(dāng)該屬性出現(xiàn)在相應(yīng)的對(duì)象枚舉屬性中。默認(rèn)為 false。

數(shù)據(jù)描述符同時(shí)具有以下可選鍵值:

value
與屬性相關(guān)的值??梢允侨魏斡行У?JavaScript 值(數(shù)值,對(duì)象,函數(shù)等)。默認(rèn)為 undefined。
writable
true 當(dāng)且僅當(dāng)可能用 賦值運(yùn)算符 改變與屬性相關(guān)的值。默認(rèn)為 false。

存取描述符同時(shí)具有以下可選鍵值:

get
一個(gè)給屬性提供 getter 的方法,如果沒有 getter 則為 undefined。方法將返回用作屬性的值。默認(rèn)為 undefined。
set
一個(gè)給屬性提供 setter 的方法,如果沒有 setter 則為 undefined。該方法將收到作為唯一參數(shù)的新值分配給屬性。默認(rèn)為 undefined。

以上是摘自MDN的解釋,看起來是很晦澀的,具體什么意思呢:
首先我們從以上解釋知道該匿名參數(shù)對(duì)象有個(gè)很好聽的名字叫屬性描述符,屬性描述符又分成兩大塊:數(shù)據(jù)描述符以及存取描述符(其實(shí)只是一個(gè)外號(hào),給指定的屬性集合起個(gè)外號(hào))。

數(shù)據(jù)描述符包括兩個(gè)屬性 : value 屬性以及 writable 屬性,第一個(gè)屬性用來聲明當(dāng)前欲修飾的屬性的值,第二個(gè)屬性用來聲明當(dāng)前對(duì)象是否可寫即是否可以修改

存取描述符就包括 get 與 set 屬性用來聲明欲修飾的象屬性的 getter 及 setter

屬性描述符內(nèi)部,數(shù)據(jù)描述符與存取描述符只能存在其中之一,但是不論使用哪個(gè)描述符都可以同時(shí)設(shè)置 configurable 屬性以及enumerable 屬性。
configurable屬性用來聲明欲修飾的屬性是否能夠配置,僅有當(dāng)其值為 true 時(shí),被修飾的屬性才有可能能夠被刪除,或者重新配置。
enumerable 屬性用來聲明欲修飾屬性是否可以被枚舉。

知道了什么是屬性描述符,我們就可以開始著手創(chuàng)建一些對(duì)象并開始配置其屬性

創(chuàng)建屬性不可配置不可枚舉的對(duì)象

//使用默認(rèn)值配置
(function () {
  var obj = {};//聲明一個(gè)空對(duì)象
  Object.defineProperty(obj,"key",{
    value:"static"
            //沒有設(shè)置 enumerable 使用默認(rèn)值 false
            //沒有 configurable 使用默認(rèn)值 false
            //沒有 writable 使用默認(rèn)值 false
  });

  console.log(obj.key);      //輸出 “static”
  obj.key = "new"         //嘗試修改其值,修改將失敗,因?yàn)?writable 為 false
  console.log(obj.key);      //輸出 “static”
  obj.a = 1;//動(dòng)態(tài)添加一個(gè)屬性
  for(var item in obj){ //遍歷所有 obj 的可枚舉屬性
     console.log(item);
  }//只輸出一個(gè) “a” 因?yàn)?“key”的 enumerable為 false
})();
//顯示配置 等價(jià)于上面
(function () {
  var obj = {};
  Object.defineProperty(obj,"key",{
    enumerable : false,
    configurable : false,
    writable : false,
    value : "static"
  })
})();
//等價(jià)配置
(function () {
  var o = {};
  o.a = 1;
  //等價(jià)于
  Object.defineProperty(o,"a",{value : 1,
                writable : true,
                configurable : true,
                enumerable : true});
  
  Object.defineProperty(o,"a",{value :1});
  //等價(jià)于
  Object.defineProperty(o,"a",{value : 1,
                writable : false,
                configurable : false,
                enumerable : false});
})();

Enumerable 特性
屬性特性 enumerable 決定屬性是否能被 for...in 循環(huán)或 Object.keys 方法遍歷得到

(function () {
  var o = {};
  Object.defineProperty(o,"a",{value :1,enumerable :true});
  Object.defineProperty(o,"b",{value :2,enumerable :false});
  Object.defineProperty(o,"c",{value :2});//enumerable default to false
  o.d = 4;//如果直接賦值的方式創(chuàng)建對(duì)象的屬性,則這個(gè)屬性的 enumerable 為 true

  for(var item in o){ //遍歷所有可枚舉屬性包括繼承的屬性
    console.log(item);
  }

  console.log(Object.keys(o));//獲取 o 對(duì)象的所有可遍歷屬性不包括繼承的屬性

  console.log(o.propertyIsEnumerable(&#39;a&#39;));//true
  console.log(o.propertyIsEnumerable(&#39;b&#39;));//false
  console.log(o.propertyIsEnumerable(&#39;c&#39;));//false
})();

輸出結(jié)果如下:

JS adds getter+setter summary

Configurable 特性

(function () {
  var o = {};
  Object.defineProperty(o,"a",{get: function () {return 1;},
                configurable : false} );
                //enumerable 默認(rèn)為 false,
                //value 默認(rèn)為 undefined,
                //writable 默認(rèn)為 false,
                //set 默認(rèn)為 undefined
                 
  //拋出異常,因?yàn)樽铋_始定義了 configurable 為 false,故后期無法對(duì)其進(jìn)行再配置
  Object.defineProperty(o,"a",{configurable : true} );
  //拋出異常,因?yàn)樽铋_始定義了 configurable 為 false,故后期無法對(duì)其進(jìn)行再配置,enumerable 的原值為 false
  Object.defineProperty(o,"a",{enumerable : true} );
  //拋出異常,因?yàn)樽铋_始定義了 configurable 為 false,set的原值為 undefined
  Object.defineProperty(o,"a",{set : function(val){}} );
  //拋出異常,因?yàn)樽铋_始定義了 configurable 為 false,故無法進(jìn)行覆蓋,盡管想用一樣的來覆蓋
  Object.defineProperty(o,"a",{get : function(){return 1}});
  //拋出異常,因?yàn)樽铋_始定義了 configurable 為 false,故無法將其進(jìn)行重新配置把屬性描述符從存取描述符改為數(shù)據(jù)描述符
  Object.defineProperty(o,"a",{value : 12});

  console.log(o.a);//輸出1
  delete o.a;   //想要?jiǎng)h除屬性,將失敗
  console.log(o.a);//輸出1
  
})();

提高及擴(kuò)展
1.屬性描述符中容易被誤導(dǎo)的地方之 writable 與 configurable

(function () {
  var o = {};
  Object.defineProperties(o,{
    "a": {
      value:1,
      writable:true,//可寫
      configurable:false//不可配置
      //enumerable 默認(rèn)為 false 不可枚舉
    },
    "b":{
      get :function(){
        return this.a;
      },
      configurable:false
    }
  });
  console.log(o.a);  //1
  o.a = 2;      //修改值成功,writable 為 true
  console.log(o.a);  //2
  Object.defineProperty(o,"a",{value:3});//同樣為修改值成功
  console.log(o.a);  //3

  //將其屬性 b 的屬性描述符從存取描述符重新配置為數(shù)據(jù)描述符
  Object.defineProperty(o,"b",{value:3});//拋出異常,因?yàn)?configurable 為 false
})();

2.通過上面的學(xué)習(xí),我們都知道傳遞屬性描述符參數(shù)時(shí),是定義一個(gè)匿名的對(duì)象,里面包含屬性描述符內(nèi)容,若每定義一次便要?jiǎng)?chuàng)建一個(gè)匿名對(duì)象傳入,將會(huì)造成內(nèi)存浪費(fèi)。故優(yōu)化如下:

(function () {
  var obj = {};

  //回收同一對(duì)象,即減少內(nèi)存浪費(fèi)
  function withValue(value){
    var d = withValue.d ||(
      withValue.d = {
        enumerable : false,
        configurable : false,
        writable : false,
        value :null
      }
      );
    d.value = value;
    return d;
  }
  Object.defineProperty(obj,"key",withValue("static"))
})();

相信看了本文案例你已經(jīng)掌握了方法,更多精彩請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!

推薦閱讀:

FileReader API的使用

vue內(nèi)置指令方法與事件

The above is the detailed content of JS adds getter+setter summary. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ??and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles