关于Object.defineProperty的get和set
2016-12-22 10:03
399 查看
Get指读取属性时调用的函数。
Set指写入属性时调用的函数。
举一个高程上的例子:
var book={
_year = 2004,
edition:1
};
Object.defineProperty(book,"year",{
get: function(){
return this._year;
},
set : function(newValue){
if (newValue > 2004){
this._year = newValue;
this.edition += newValue -2004;
}
}
});
book.year =2005;
alert(book.edition); //2
开始,当book.year=2005时,get获取到this._year的值,然后传值给set,保存新值,this.year=newValue=2005,this.edition=2。同理,将book.year改为2006,那么edition的值应为3,2014应为1.
我开通博客 并写些东西,仅仅是为了自己学到的新东西作为记录,方便以后自己查看,写的很差,大家多给些意见,少些讽刺。谢谢大家。
Set指写入属性时调用的函数。
举一个高程上的例子:
var book={
_year = 2004,
edition:1
};
Object.defineProperty(book,"year",{
get: function(){
return this._year;
},
set : function(newValue){
if (newValue > 2004){
this._year = newValue;
this.edition += newValue -2004;
}
}
});
book.year =2005;
alert(book.edition); //2
开始,当book.year=2005时,get获取到this._year的值,然后传值给set,保存新值,this.year=newValue=2005,this.edition=2。同理,将book.year改为2006,那么edition的值应为3,2014应为1.
我开通博客 并写些东西,仅仅是为了自己学到的新东西作为记录,方便以后自己查看,写的很差,大家多给些意见,少些讽刺。谢谢大家。
相关文章推荐
- Object类 Object常用成员方法
- boost.numpy编译报错:undefined reference to `PyInt_FromLong' libboost_numpy.so: undefined reference to `PyCObject_AsVoidPtr'
- 为什么用Object.prototype.toString.call(obj)检测对象类型?
- ECMAScript6(ES6)标准之对象Object扩展方法及新特性
- 《Effective Objective-C 2.0》读书笔记---第四章
- python 3.5: TypeError: a bytes-like object is required, not 'str'
- READING NOTE: Beyond Skip Connections: Top-Down Modulation for Object Detection
- python 2.7 : 引用模块时出现TypeError:'module' object is not callable
- JavaScript与Objective-C之间的通信
- 第3章 基本概念(3)数据类型:Number类型 String类型 Object类型
- Exception in thread "main" java.lang.RuntimeException: Cannot instantiate object of type com.gatz.d
- 【.NET调用Python脚本】C#调用python requests类库报错 'module' object has no attribute '_getframe' - IronPython 2.7
- JSONObject, JSONArray来构建json文本
- 《Effective Objective-C 2.0》读书笔记---第三章
- Struts 返回jsonObject是空的
- 在项目引用里添加上对Microsoft Word 11.0 object library的引用
- 在项目引用里添加上对Microsoft Word 11.0 object library的引用
- 关于view的drawRect多次被调用出现绘图重叠问题
- Error occurred during initialization of VM Could not reserve enough space for object heap Could not
- List<Map<String, Object>>