简体   繁体   English

ES6 getter setter和JSON对象

[英]ES6 getter setter with JSON object

According to this doc 根据这份文件

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/set

You can do something like this 你可以做这样的事情

var o = {
  set current (str) {
    this.log[this.log.length] = str;
  },
  log: []
}

But what if I want the current variable to be object and I want to do setter on a property of that object? 但是,如果我希望current变量成为对象,并且想对该对象的属性进行setter ,该怎么办?

The below doesn't seem to work 以下似乎不起作用

var o = {
  set current.myVal (str) {
    this.log[this.log.length] = str;
  },
  log: []
}

What is the correct way to do this? 正确的方法是什么? I read that you can use expression but there is no example. 我读到您可以使用expression但没有示例。

** UPDATE 1 ** **更新1 **

One of the answers below is correct but what if it's class ? 以下答案之一是正确的,但如果是class怎么办?

class o {
  set current.myVal (str) {
    this.log[this.log.length] = str;
  }
}

I tried below and didn't work 我在下面尝试过,没有工作

class o {
  current: {
    set myVal(str) {
      o.log.push(str);
    }
  }
}

You seem to be looking for 您似乎在寻找

var o = {
  current: {
    set myVal(str) {
      o.log.push(str);
    }
  },
  log: []
};

But that's probably a bad idea. 但这可能是一个坏主意。

I don't think this is a good idea, but theoretically you can return an object with a setter for o.current : 我认为这不是一个好主意,但是从理论上讲,您可以使用o.current的setter返回一个对象:

 var o = { get current() { var self = this; return { set myVal(str) { self.log[self.log.length] = str; } } }, log: [] }; o.current.myVal = 1234; o.current.myVal = 5678; document.write(o.log) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM