对象访问器 getter和setter

2021-03-02  本文已影响0人  web_jianshu
var person = {
        firstName: "Bill",
        lastName: "Gates",
        language: "en",
        get lang() { // 自动解析为 lang: return this.language
          return this.language;
        },
        set lang(value) {
          this.language = value;
        }
      };
      console.log(person.lang); // => "en"
      person.lang = "chinese";
      console.log(person); // => {firstName: "Bill", lastName: "Gates", language: "chinese"}
      console.log(person.lang); // => "chinese"
例子1
      var person = {
        firstName: "Bill",
        lastName: "Gates",
        fullName: function() {
          return this.firstName + " " + this.lastName;
        }
      };
      console.log(person.fullName()); // => Bill Gates 以方法的形式访问

例子2
      var person = {
        firstName: "Bill",
        lastName: "Gates",
        get fullName() { // 自动解析为 fullName: "Bill Gates"
          return this.firstName + " " + this.lastName;
        }
      };
      console.log(person); // => {firstName: "Bill", fullName: "Bill Gates", lastName: "Gates"}
      console.log(person.fullName); // => Bill Gates 以属性形式访问, 提供了更简洁的语法。

模拟js操作客户端的cookie
      let doc = {
        arp_scroll_position: 414,
        PHPSESSID: "65trladb2tjqbikl0fn93akkbu",
        get cookie() {
          let str = "";
          for (let key in this) {
            if (key !== "cookie") {
              str += key + "=" + this[key] + ";";
            }
          }
          return str.slice(0, -1);
        },
        set cookie(value) {
          let arr = value.split(";");
          for (let item of arr) {
            let [a, b] = item.split("=");
            this[a] = b;
          }
        }
      };

      doc.cookie = `app-installed=1; expires=${new Date(
        2020,
        11,
        11
      ).toGMTString()}`;
      console.log(doc); // => {" expires": "Thu, 10 Dec 2020 16:00:00 GMT", PHPSESSID: "65trladb2tjqbikl0fn93akkbu", app-installed: "1", arp_scroll_position: 414, cookie: "arp_scroll_position=414;PHPSESSID=65trladb2tjqbikl0fn93akkbu;app-installed=1; expires=Thu, 10 Dec 2020 16:00:00 GMT"}

      console.log(doc.cookie); // => arp_scroll_position=414;PHPSESSID=65trladb2tjqbikl0fn93akkbu;app-installed=1; expires=Thu, 10 Dec 2020 16:00:00 GMT
上一篇下一篇

猜你喜欢

热点阅读