get 演算子、set 演算子で代入操作を宣言できる
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get/set</title>
<script type="text/javascript">
/* ==================== SCRIPTS ==================== */
var Clazz = function(val) {
if (val) {
this._value = val;
}
}
Clazz.prototype = {
_value : '',
get value(){
return this._value;
},
set value(val) {
this._value = val;
}
};
function exec() {
var obj = new Clazz('test1');
document.getElementById('trace1').innerHTML = '// obj.value is ' + obj.value + ' now';
obj.value = 'test2';
document.getElementById('trace2').innerHTML = '// obj.value is ' + obj.value + ' now';
}
/* ==================== SCRIPTS ==================== */
</script>
</head>
<body>
<div>var obj = new Clazz('test1');</div>
<div id="trace1">// obj.value is ??? now</div>
<div>obj.value = 'test2';</div>
<div id="trace2">// obj.value is ??? now</div>
<button onclick="exec()">execute</button>
</body>
</html>
[source] [reload] |