Home  >  Article  >  Web Front-end  >  Usage examples of get and set of classes in ES6 javascript

Usage examples of get and set of classes in ES6 javascript

小云云
小云云Original
2018-01-04 09:17:5312256browse

This article mainly introduces the usage of get and set of class classes in ES6 javascript, and analyzes the usage of get and set keywords of classes in ES6 based on specific examples. Friends who need it can refer to it. I hope it can help everyone.

Same as ES5, you can use the get and set keywords inside Class to set the storage function and the value function for a certain attribute to intercept the access behavior of the attribute.


class MyClass {
  constructor() {
    // ...
  }
  get prop() {
    return 'getter';
  }
  set prop(value) {
    console.log('setter: ' + value);
  }
}
let inst = new MyClass();
inst.prop = 123;
// setter: 123
inst.prop
// 'getter'

In the above code, the prop attribute has a corresponding storage function and a value function, so the assignment and reading behaviors are customized.

The storage function and the value function are set on the descriptor object of the attribute.


class CustomHTMLElement {
  constructor(element) {
    this.element = element;
  }
  get html() {
    return this.element.innerHTML;
  }
  set html(value) {
    this.element.innerHTML = value;
  }
}
var descriptor = Object.getOwnPropertyDescriptor(
  CustomHTMLElement.prototype, "html");
"get" in descriptor // true
  "set" in descriptor // true

In the above code, the storage function and the value function are defined on the description object of the html attribute, which is completely consistent with ES5.

Related recommendations:

Example description of how to use the functions get and set

How to use the Set data structure to operate arrays in ES6

Sharing of Sql optimization examples where the offset is too large during mysql paging

The above is the detailed content of Usage examples of get and set of classes in ES6 javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn