Home > Web Front-end > JS Tutorial > Take you to understand the Object.defineProperty() method in three minutes

Take you to understand the Object.defineProperty() method in three minutes

醉折花枝作酒筹
Release: 2021-04-23 09:11:31
forward
1945 people have browsed it

This article will give you a detailed introduction to the Object.defineProperty() method. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Take you to understand the Object.defineProperty() method in three minutes

Syntax

Object.defineProperty(obj, prop, descriptor)

Definition

Define a new attribute on the object and modify the original attribute!

Parameters

obj Target object.

prop The name of the property to be defined or modified.

descriptor Property descriptor defined or modified. (The values ​​of value, writable and get and set cannot be set at the same time)

Attribute descriptor

configurable: Boolean --> Is it possible? Configuration

enumerable: Boolean--> Whether it can be enumerated

value: Default value

writable: Boolean--> Whether it can be overridden

/Access (access) descriptor

get //The callback function dynamically calculates the value of the current attribute based on other attributes

set //The callback function monitors the current attribute Whether the value changes and then updates other related properties

Return value

Return the object being operated on, that is, return obj parameter

The following code is a simple implementation Two-way data binding:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" id="ipt" />
    <p id="lc"></p>
  </body>
</html>
<script>
  //获取页面元素
  var ipt = document.getElementById("ipt");
  var ps = document.getElementById("lc");

  var obj = { name: "" };

  Object.defineProperty(obj, "name", {
    get() {
      return ipt.value;
    },
    set(newval) {
      ipt.value = newval;
      ps.innerHTML = newval;
    },
  });

  ipt.addEventListener("keyup", function() {
    ps.innerHTML = ipt.value; //数据赋值
  });
</script>
Copy after login

Effect picture display:

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of Take you to understand the Object.defineProperty() method in three minutes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template