js的数据属性:P139
(1)[[Configurable]]
(2)[[Enumerable]]
(3)[[Writable]]
(4)[[Value]]
使用Object.definerPropert()方法修改属性的默认值,接收的参数:
(1)属性所在的对象
(2)属性的名字
(3)一个描述符对象(Configurable,Enumerable,Writable,Value)
// 'use strict'
var person = {
name: "Jack",
age: 12,
job: "Software Engineer",
sayname: function(){
console.log(this.name);
}
};
console.log(person.name);//Jack person.name = "Mei";
console.log(person.name);//Mei Object.defineProperty(person,"name",{
writable: false,
value: "Nice"
})
console.log(person.name);//Nice person.name = "Li";//在非严格模式下,赋值操作会被忽略,严格模式下,会抛出错误。Uncaught TypeError: Cannot assign to read only property 'name' of object '#<Object>'
console.log(person.name);//Nice Object.defineProperty(person, "name", {
configurable: false,//设置为false则不能修改属性的特性。
value: "Nice"
}) Object.defineProperty(person, "name", {
configurable: true, // TypeError: Cannot redefine property: name at Function.defineProperty (<anonymous>) at js_tesr.html:37
value: "Nice"
}) Object.defineProperty(person,"name",{
writable:true //Uncaught TypeError: Cannot redefine property: name at Function.defineProperty (<anonymous>)
//将writable设置为false则不报错。
}) Object.defineProperty(person,"name",{});//疑问:P140倒数第三行: 三个属性默认为false,但是这里还是可以修改name的属性值。
person.name = "Li";
console.log(person.name);//Li //2.访问器属性
//设置一个属性导致其他属性发生变化 var book = {
year:2004,
edition : 1
}; Object.defineProperty(book,'year',{
//get:在读取属性时调用的函数
get: function(){
return this._year;//_下划线表示只能通过对象方法访问到的属性
}, //set:在写入属性时调用的函数
set: function(newValue){
if(newValue > 2004){
this._year = newValue;
this.edition += newValue - 2004;
}
}
}); book.year=2005;
console.log(book.edition);// //访问器属性——模拟vue双向数据绑定功能。
var obj ={};
Object.defineProperty(obj, "hello",{
//写入属性时调用的函数
set :function(newVal){
document.getElementById("input").value = newVal;
document.getElementById("content").innerHTML = newVal;
}
});
document.addEventListener("keyup",function(e){
obj.hello = e.target.value;
});