• JS中的setter、getter数据存取器


    1. JS属性可分为两种类型
      ① 数据属性
         只是简单存储了一个值
      ② 存取器属性
         最大的特点是在设置、获取属性值的时候能够做一些其他的操作

    2. 设置存取器属性的两种方式
      ① 直接在对象中设置

      let obj = {
      	count: 5, // 普通的数据属性
      	// index为存取器属性
      	_index: 1,  // _index用来存储index值
      	set index(value) {
      		console.log("可以在设置index值之前,做一些其他的操作");
      		this._index = value;
      		console.log("index值设置完毕");
      		console.log("可以在设置index值之后,做一些其他的操作");
      	},
      	get index() {
      		console.log("可以在获取index值之前,做一些其他的操作");
      		return this._index;
      	}
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

      在这里插入图片描述

      ②对象已存在的情况下,利用Object.defineProperty方法追加存取器属性及特性

      let person = {    // person对象已存在
      	name: 'wuwu',
      	age: 18
      }
      let _sex = 'nv';  // _sex用来存储sex值
      Object.defineProperty(person, 'sex', {
      	// value: _sex,   // 与get方法不能共存,因为获取value值等同于调用get方法
      	// writable: true, // 与set方法不能共存,因为有set方法默认就是可写的
      	enumerable: true, // 是否可遍历
      	configurable: true, // 是否可删除
      	set(value) {
      		console.log("可以在设置index值之前,做一些其他的操作");
      		_sex = value;
      		console.log("index值设置完毕");
      		console.log("可以在设置index值之后,做一些其他的操作");
      	},
      	get() {
      		console.log("可以在获取index值之前,做一些其他的操作");
      		return _sex;
      	}
      });
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21

      在这里插入图片描述

    3.利用Object.getOwnPropertyDescriptor()方法获取属性的特性

    Object.getOwnPropertyDescriptor(person, 'sex');
    
    • 1

    在这里插入图片描述

  • 相关阅读:
    手机玩潜水员戴夫?GameViewer远程如何随时随地玩潜水员戴夫教程
    springboot web项目中 Set-Cookie 失败 办法
    Django-request请求
    有哪些好的科研工具软件?
    PMP每日一练 | 考试不迷路-10.22(包含敏捷+多选)
    Spring SpringMVC MyBatis SpringBoot 重要概念
    springboot中使用redis管理session
    Spring cloud gateway过滤器学习
    国产MCU芯片(2):东软MCU概览
    c#委托、lambda、事件
  • 原文地址:https://blog.csdn.net/wytccc/article/details/128034529