get and set
(function () { function Student(name, age, gender) {
this._name = name;
this._age = age;
this._gender = gender;
} Object.defineProperty(Student.prototype, "name", {
get: function () {
return this._name;
},
set: function (value) {
this._name = value;
}
});
Object.defineProperty(Student.prototype, "age", {
get: function () {
return this._age;
},
set: function (value) {
this._age = value;
}
});
Object.defineProperty(Student.prototype, "gender", {
get: function () {
return this._gender;
}
}); var stu = new Student("张三", 12, "男");
console.log(stu.name);
stu.age=13;
console.log(stu.age);
})();
在只提一下Object.defineProperty方法。
三个参数:目标对象,方法名,功能(get和set)
注意set只能接受一个数值。
今天偶然想到,set的一个巧用。用它可以代替形参,有时候。具体是不去写形参,而是在用它的时候去拿set去赋值。
代码进化:
(function () { function Student(name, age, gender) {
this._name = name;
this._age = age;
this._gender = gender;
} Object.defineProperties(Student.prototype, {
name: {
set: function (value) {
this._name = value;
},
get: function () {
return this._name;
}
},
age: {
set: function (value) {
this._age = value;
},
get: function () {
return this._age;
}
},
gender: {
get: function () {
return this._gender;
}
}
}); function main() {
var stu1 = new Student("Tom", 12, "boy");
console.log(stu1.gender);
} main();
})();
这里用Object.defineProperties批量设置属性。注意格式就行。
代码装甲进化:
(function () { function Student(name, age, gender) {
return {
_name: name,
_age: age,
_gender: gender,
get name() {
return this._name;
},
set name(value) {
this._name=value;
},
get age(){
return this._age;
},
set age(value){
this._age=value;
},
get gender(){
this._gender=gender;
}
}; } var stu1=new Student("Tom",12,"female");
console.log(stu1.name);
})();
这样可以把get和set写在内部。同样注意格式。
随机推荐
- [php]Maximum function nesting level of '100' reached错误
今天在做后台一个模块的时候报出了这个错误. Maximum function nesting level of '100' reached 仔细分析之后发现是在类的初始化过程中(__construct ...
- Bootstrap 第一天
Bootstrap第一天 1.什么是Bootstrap? Bootstrap是由两位设计开发的. Bootstrap主要是前端的框架(HTML.CSS.JS). 2.为什么使用Boot ...
- QT设置TextEdit颜色
//设置textEdit颜色 QPalette palette= ui->receiveTextEdit->palette(); palette.setColor(QPalette::Ba ...
- Yii2 提供可以用属性的方式去获取类的一个方法
刚开始用 Yii 的小朋友可能对下面的写法非常疑惑: public function actionIndex() { $user = User::find()->where(['name'=&g ...
- slam kf
一.KF 1.从概率来理解概率估计因为希望整个运动估计较长时间内最优,所以反而会用最新的知识去更新之前的状态,就比如在做完当前帧的位姿估计的时候,修改局部地图的路标点.如果站在之前的状态上来考虑,用的 ...
- 【转】RMQ-ST算法详解
地址:http://blog.csdn.net/z287438743z/article/details/8132806 RMQ(Range Minimum/Maximum Query)问题就是求区间最 ...
- Java 环境变量设置 -- JAVA_HOME CLASSPATH
1.打开我的电脑--属性--高级--环境变量 2.新建系统变量JAVA_HOME 和CLASSPATH 变量名:JAVA_HOME 变量值:C:\Program Files\Java\jdk1.7.0 ...
- 在CentOS安装CMake
http://www.cnblogs.com/mophee/archive/2013/03/19/2969456.html 一.环境描述 1.系统:CentOS 6.4 i386 (min) 2.登录 ...
- Hive- Hive 按时间定期插入分区表
写个shell脚本Hive 按时间定期插入分区表,由于今天统计的是昨天的数据所以日期减一. #!/bin/bash DT=`date -d '-1 day' "+%Y-%m-%d" ...
- linux shell 编程(一)
脚本:命令的堆砌,按照实际需要结合命令流程控制机制实现的源程序 linux 内核只能识别 elf格式的文件(可执行的可链接的文件) 脚本的第一行写 #!/bin/bash 表示脚本解释器