不积跬步,无以至千里。

我的学习笔记

首页

空明百问

编程题

内容更新于: 2022-06-29 08:21:28

对象取值递归

前言:一道小编程题,每次取值之后所取出的值都会自增一,具体如下所示。

题目如下

目标: let a = {}; console.log(a.x) // 1 console.log(a.x) // 2 console.log(a.x) // 3

方法一


// 1.defineProperty
let a = {};
Object.defineProperty(a, 'x', {
  get: function () {
    if (!this.b) {
      this.b = 0;
    }
    return this.b++;
  },
  set: function (val) {
    this.b = val;
  }
});


方法二


// 2.Proxy
let a = {};
a = new Proxy(a, {
  get: function (target, key) {
    if (key === 'x') {
      return target[key] = (target[key] || 0) + 1;
    }
    return target[key];
  }
})


方法三


// 3.利用相等的隐式转换 会调用valueOf方法
let a = {};
a.x = 0;
a.valueOf = function () {
  return this.x++;
}
console.log('a', a == 0 && a == 1)
console.log(a.x)
console.log('a', a == 2)
console.log(a.x)


本文结束