代码如下:
function Sandy(val){
var value = val;
this.getValue = function(){
return value;
};
this.setValue = function(val){
value = val;
};
}
//usage
var sandy = new Sandy("test");
sandy.value
// => undefined
sandy.setValue("test2")
sandy.getValue
代码如下:
function makeProperty(o, name, predicate) {
var value; //This is property value;
//The setter method simply returns the value
o['get' + name] = function() { return value;};
//The getter method stores the value or throws an exception if
//the predicate rejects the value
o['set' + name] = function(v) {
if (predicate && !predicate(v) {
throw 'set' + name + ': invalid value ' + v;
} else {
value = y;
}
}
}
//The following code demenstrates the makeProperty() method
var o = {}; // Here is an empty object
//Add property accessor methods getName and setName
//Ensure that only string values are allowed
makeProperty(o, 'Name', function(x) { return typeof x == 'string'; });
o.setName('Frank'); //Set the property value;
print(o.getName()); //Get the property value
o.setName(0); //Try to set a value of the wrong type
代码如下:
function Sandy(val){
var value = val,
_watch = function(newVal) {
console.log('val is Changed to : ' + newVal);
}
this.__defineGetter__("value", function(){
return value;
});
this.__defineSetter__("value", function(val){
value = val;
_watch(val);
});
}
var sandy = new Sandy("test");
sandy.value
// => test
sandy.value = "test2";
// => 'val is Changed to : test2'
sandy.value
// => "test2"
代码如下:
function Sandy(val){
this.value = val;
}
Sandy.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
//Or
var sandy = {
'_value' : 'sandy',
get value() {
return this._value;
},
set value(val) {
this._value = val;
}
}
代码如下:
var sandy = {}, rValue;
Object.defineProperty(sandy, 'value' ,
{
'set' : function(val) {
rValue = val;
},
'get' : function() {
return rValue;
},
'enumerable' : true,
'configurable' : true
}
)
//Ie8+
Object.defineProperty(document.body, "description", {
get : function () {
return this.desc;
},
set : function (val) {
this.desc = val;
}
});
document.body.description = "Content container";
// document.body.description will now return "Content container"