Home >Web Front-end >JS Tutorial >Take you to understand the Object.defineProperty() method in three minutes
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.
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>
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!