js的数据属性:P139
(1)[[Configurable]]
(2)[[Enumerable]]
(3)[[Writable]]
(4)[[Value]]
使用Object.definerPropert()方法修改属性的默认值,接收的参数:
(1)属性所在的对象
(2)属性的名字
(3)一个描述符对象(Configurable,Enumerable,Writable,Value)
1 // 'use strict' 2 var person = { 3 name: "Jack", 4 age: 12, 5 job: "Software Engineer", 6 sayname: function(){ 7 console.log(this.name); 8 } 9 }; 10 console.log(person.name);//Jack 11 12 13 person.name = "Mei"; 14 console.log(person.name);//Mei 15 16 Object.defineProperty(person,"name",{ 17 writable: false, 18 value: "Nice" 19 }) 20 console.log(person.name);//Nice 21 22 person.name = "Li";//在非严格模式下,赋值操作会被忽略,严格模式下,会抛出错误。Uncaught TypeError: Cannot assign to read only property 'name' of object '#<Object>' 23 console.log(person.name);//Nice 24 25 Object.defineProperty(person, "name", { 26 configurable: false,//设置为false则不能修改属性的特性。 27 value: "Nice" 28 }) 29 30 Object.defineProperty(person, "name", { 31 configurable: true, // TypeError: Cannot redefine property: name at Function.defineProperty (<anonymous>) at js_tesr.html:37 32 value: "Nice" 33 }) 34 35 Object.defineProperty(person,"name",{ 36 writable:true //Uncaught TypeError: Cannot redefine property: name at Function.defineProperty (<anonymous>) 37 //将writable设置为false则不报错。 38 }) 39 40 Object.defineProperty(person,"name",{});//疑问:P140倒数第三行: 三个属性默认为false,但是这里还是可以修改name的属性值。 41 person.name = "Li"; 42 console.log(person.name);//Li 43 44 45 //2.访问器属性 46 //设置一个属性导致其他属性发生变化 47 48 49 var book = { 50 year:2004, 51 edition : 1 52 }; 53 54 Object.defineProperty(book,'year',{ 55 //get:在读取属性时调用的函数 56 get: function(){ 57 return this._year;//_下划线表示只能通过对象方法访问到的属性 58 }, 59 60 //set:在写入属性时调用的函数 61 set: function(newValue){ 62 if(newValue > 2004){ 63 this._year = newValue; 64 this.edition += newValue - 2004; 65 } 66 } 67 }); 68 69 book.year=2005; 70 console.log(book.edition);//2 71 72 73 //访问器属性——模拟vue双向数据绑定功能。 74 var obj ={}; 75 Object.defineProperty(obj, "hello",{ 76 //写入属性时调用的函数 77 set :function(newVal){ 78 document.getElementById("input").value = newVal; 79 document.getElementById("content").innerHTML = newVal; 80 } 81 }); 82 document.addEventListener("keyup",function(e){ 83 obj.hello = e.target.value; 84 });