基本特征:面向对象编程有三个基本特征:封装、继承、多态;
面向对象思想:JavaScript 语言是通过一种叫做 原型(prototype)的方式来实现面向对象编程的。对象(object)则是依靠 构造器(constructor)利用 原型(prototype)构造出来的;
属性类型:数据属性、访问器属性
数据属性:包含一个数据值的位置,可以读取和写入;包括4个描述其行为的特性: configurable、enumerable、writeable、value
要想修改属性默认的特征:使用Object.defineProperty() 接收三个参数,属性所在对象、属性的名字、修改的描述符对象;
访问器属性:包含一对儿getter和setter函数,读取访问器属性时,调用getter函数,这个函数负责返回有效的值;写入访问器属性时,调用setter函数并传入新值;
访问器属性有4个特性:configurable、enumerable、get、set、
访问器属性不能直接定义,必须使用,Object.defineProperty()
var person={
_year:2018, //直接定义数据属性_year
num:1
};
console.log("这是开始:"+person._year);
Object.defineProperty(person,"year",{ //使用Object.defineProperty()定义访问器属性year
get:function(){
return this._year;
},
set:function(newvalue){
if(newvalue>2018){
this._year=200;
this.num+=newvalue-2018;
}
}
});
person.year=2020;
console.log(person.num); //3
console.log(person._year); //200
定义多个属性 Object.defineProperties() 接收两个参数:要添加或修改属性的对象 要添加的属性对象
var school={};
Object.defineProperties(school,{
_year:{ //定义两个数据属性
value:100
},
num:{
value:2
},
year:{ //定义一个访问器属性 year
get:function(){
return 200;
},
set:function(newvalue){
this._year=newvalue;
this.num+=1;
}
}
});
读取属性的特性 :Object.getOwnPropertyDescriptor() 接收两个参数,属性所在对象 和要读取描述符的属性名称;
原文:https://www.cnblogs.com/yongyang/p/8902542.html