JavaScript面向对象--记录防忘记(一)

时间:2021-10-05 21:45:55

1、理解对象:

创建自定义对象最简单的方式就是创建一个object实例,再给他添加属性和方法。

let person = new Object();
person.name = 'zhangsan';
person.age = 25;
person.sayName = function (){alert(this.name)};
//=============================

以上实例现在可以这样写:

let person = {
name:'zhangsan',
age:25
sayName:function(){
alert(this.name);
}
}

2、属性类型

  数据属性,访问器属性

Value:这个属性的属性值

let person = {};
Object.defineProperty(person,"name",{
value:"ZhangSan"
});
let person = {};
Object.defineProperty(person,"age",{
value:25
});

Configurbale:表示是否能通过Delete删除属性并重定义,能否修改属性的特性,这个属性的默认值是true;

let person = {};
Object.defineProperty(person,"name",{
configurable:true,
value:"ZhangSan"
});
Object.defineProperty(person,"age",{
configurable:false,
value:25
});
delete person.name;
delete person.age;
alert(person.name);//输出 undefined
alert(person.age);//输出 25 Object.defineProperty(person,"age",{
configurable:true,//抛出错误,configurable为false后无法重定义;
value:25
});

Enumable:为false的时候无法for-in循环返回属性,当使用new Object创建实例的时候默认是false,直接定义为true;

Writable:是否可以修改属性的值,默认是true;

let person = {};
Object.defineProperty(person,"name",{
writable:true,
value:"ZhangSan"
});
Object.defineProperty(person,"age",{
writable:false,
value:25
});
person.name = 'lisi';
person.age = 33;
alert(person.name);//输出 lisi
alert(person.age);//输出 25

访问器属性不包含数值,它们包含一对getter和setter函数;

Get:Set:默认值都是undefined

let book = {
edition: 1
};
Object.defineProperty(book, "_year", {
get: function () {
return this.year;
},
set: function (newValue) {
if (newValue > 2004) {
this.year = newValue;
this.edition += newValue - 2004;
console.log(newValue);
}
}
});
book.year = 2005;
alert(book.year);// 输出2005
alert(book.edition);// 输出2

在不支持Object.defineProperty()方法的浏览器中不能修改[Configurable],和[Enumerable]。

3、定义多个属性

let book = {};
Object.defienProperties(book,{
year:{
writable:true,
value:2004
}
edition:{
writable:true,
value:1
}
});

4、读取属性的特性

==