defineProperty定义属性的作用
defineProperty定义属性的作用<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>defineProperty定义属性的作用</title></head>
<body> <script> // 给定需求 定义一个fullName属性,要求姓和名更改 fullName要同时更改 fullName更改 firstName和lastName也要同时更改 var person = { firstName: 'A', lastName: 'B' } Object.defineProperty(person, "fullName", { // get()函数不手动调用也会自己运行 说明是回调函数 关于回调函数的3个问题 /* 1. 什么时候执行 2. 用来做什么? 3.this是谁 */ get() { // 监听当访问被传入属性的时候执行, 将函数的返回值作为属性值, this是属性所在的对象 return this.firstName + '-' + this.lastName }, set(value) { // 当修改了被传入属性的时候执行,用来监听属性值的变化, this是属性所在的对象 // console.log(value); this.firstName = value.split('-')[0] this.lastName = value.split('-')[1] } }) var test = 1; if (test === 1) { person.firstName = 'c' console.log(person);
} test = 2; if (test === 2) { person.fullName = 'X-Y' console.log(person);
}
// 看完应该就明白了吧 感谢关注前端小曹 </script></body>
</html>