Javascript override parameter value before installation

What I really want to do is:

Blog.prototype = {
  set content(content) {
    this.content = JSON.parse(content);
  }
}

However, this leads to infinite recursion.

I know I can do something like:

  set content(content) {
    this._content = JSON.parse(content);
  },

  get content() {
    return this._content;
  }

However, when I do JSON.stringify(blog), it does not include content, but includes _content, which is undesirable.

How can i do this?

+4
source share
3 answers

Make the variable "_content" non-enumerable.

Blog.prototype = {
  set content(newContent) {
    Object.defineProperty(this, "_content", { 
      value: JSON.parse(newContent), 
      writable: true 
    });
  },
  get content() {
    return this._content;
  }
};

By default, the flag is "enumerable" for the property of the object falseif it is not explicitly specified in the call defineProperty().

- Symbol , , . IE :

Blog.prototype = () => {
  const internalContent = Symbol("content key");
  return {
    set content(newContent) {
      this[internalContent] = newContent;
    },
    get content() {
      return this[internalContent];
    }
  };
}();

JSON.stringify(), defineProperty(). Symbol , . Symbol, Symbol(), .

+4

Set Get with _content .toJson(), JSON.stringify content _content.

toJSON() {
  return {
    content: this._content
  }
}

MDN .toJson() :

, jSON, , toJSON() JSON : , toJSON() , .


-

function Blog() {}

Blog.prototype = {
  set content(content) {
    this._content = JSON.parse(content);
  },

  get content() {
    return this._content;
  },
  
  toJSON() {
    return {
      content: this._content
    }
  }
};

var blog = new Blog();

blog.content = '{ "a": "5" }';

console.log(blog.content);

console.log(JSON.stringify(blog));

ES6

class Blog {
  set content(content) {
    this._content = JSON.parse(content);
  }

  get content() {
    return this._content;
  }
  
  toJSON() {
    return {
      content: this._content
    }
  }
};

const blog = new Blog();

blog.content = '{ "a": "5" }';

console.log(blog.content);

console.log(JSON.stringify(blog));
+1

I was able to solve this by building Lucky's answer:

var Blog = function () {
  var content;

  Object.defineProperty(this, "content", {
    get: function() {
      return content;
    },
    set: function(value) {
      content = JSON.parse(value);
    },
    enumerable: true,
  });
};

The trick here is the flag enumerable, which is false by default.

+1
source

Source: https://habr.com/ru/post/1663469/


All Articles