vue--defineProperty

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    var o = {}; // 创建一个新对象

// 在对象中添加一个属性与数据描述符的示例
// Object.defineProperty(o, "a", {
//   value : 37,
//   writable : true,
//   enumerable : true,
//   configurable : true
// });

// 对象o拥有了属性a,值为37

// 在对象中添加一个属性与存取描述符的示例
var bValue;
Object.defineProperty(o, "b", {
  get : function(){
    return bValue;
  },
  set : function(newValue){
      console.log(newValue)
    bValue = newValue;
  },
  enumerable : true,
  configurable : true
});

o.b = 38;
console.log(bValue)
// 对象o拥有了属性b,值为38

// o.b的值现在总是与bValue相同,除非重新定义o.b

// 数据描述符和存取描述符不能混合使用
// Object.defineProperty(o, "conflict", {
//   value: 0x9f91102, 
//   get: function() { 
//     return 0xdeadbeef; 
//   } 
// });
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
</script>
</html>
原文地址:https://www.cnblogs.com/x-yy/p/13099795.html