标签:
1.ES5的属性特性包括下面六个:
var person = {}; Object.defineProperty(person, "name", { writable: false,//设置属性的特性为不可修改的 value: "Tom" //把name属性值设为Tom }); person.name = "Jany"; //试图把name属性值设置为Jany,但是失败了.非严格模式下会忽略此语句,严格模式则会报错的 console.log(person.name); //结果仍然为Tom
var person = {}; Object.defineProperty(person, "name", { configurable: false, //把configurable设置为false value: "Tom" }); console.log(person.name); //打印结果为Tom delete person.name; //试图删除name属性 console.log(person.name); //但是name仍然存在,打印出Tom
var person = {}; Object.defineProperty(person, "name", { configurable: true, value: "Tom" }); console.log(person.name); //打印出Tom delete person.name; //试图删除name属性 console.log(person.name); //删除成功,打印出udefined
var person = {};
//把person.name属性的configurable设置为false; Object.defineProperty(person, "name", { configurable: false, value: "Tome" }); //然后试图重新把person.name属性的configurable设置为true;但是浏览器出现报错信息。 Object.defineProperty(person, "name", { configurable: true, value: "lyl" }); console.log(person.name);
//定义一个对象book var book = { _year: 2004, //出版年份 edition: 1 //版本号 };
//定义year属性的特性 Object.defineProperty(book, "year", {
//重写get方法,即如果我们试图book.year获取year值时,实质上是获取book._year的值 get: function() { return this._year; },
//重写了set方法,每当对book.year进行赋值时,则相应的修改book._year和book.edition的值 set: function(newValue) { if(newValue > 2004) { this._year = newValue; this.edition += newValue - 2004; } } }); book.year = 2005; console.log(book.edition); //2
var book = {}; Object.defineProperties(book, {
// 定义一个新的属性_year,并且他的值为2004 _year: { value: 2004 },
// 定义一个新的属性edition,并且他的默认值是1,而且属性值是可修改的 edition: { value: 1, writable: true// 可修改的 },
// 定义一个新的属性year,并且重写了他的get和set方法 year: { get: function() { return this._year; }, set: function(newValue){ if(newValue > 2004) { //alert("ok"); this._year = newValue; this.edition += newValue-2004; } } } }); book.year = 2006; console.log(book.edition);//3
读取属性的特性,使用Object.getOwnPropertyDescriptor方法
var book = {};
// 为该对象定义一些属性 Object.defineProperties(book, { _year: { value: 2004 }, edition: { value: 1, writable: true// 可修改的 }, year: { get: function() { return this._year; }, set: function(newValue){ if(newValue > 2004) { //alert("ok"); this._year = newValue; this.edition += newValue-2004; } } } }); //获取_year属性的特性 var descriptor1 = Object.getOwnPropertyDescriptor(book, "_year"); console.log(descriptor1.configurable); //false console.log(descriptor1.enumberable); //undefinded console.log(descriptor1.writable); //false console.log(descriptor1.value); //2004 console.log(descriptor1.get); //undefined console.log(descriptor1.set); //undefined console.log("\n"); //获取year属性的特性 var descriptor2 = Object.getOwnPropertyDescriptor(book, "year"); console.log(descriptor2.configurable); //false console.log(descriptor2.enumberable); //undefined console.log(descriptor2.writable); //undefined console.log(descriptor2.value); //undefined console.log(descriptor2.get); //function() console.log(descriptor2.set); //function(value)
标签:
原文地址:http://www.cnblogs.com/yugege/p/4823863.html