是否可能为所有JavaScript对象定义通用的getter/setter?
下面是我想要实现的伪代码。基本上,person和animal路由getter和setter到CustomGetter和CustomSetter。
function NewPerson()
{
var person;
var animal;
var person.name = 'John Doe';
console.log("Name: " + person.name); //Prints "Name: JOHNDOE CUSTOM"
var animal.type = 'Herbivore';
console.log("Animal: " + animal.type); //Prints "Animal: HERBIVORE CUSTOM"
console.log("Age: " + person.age); //Prints "Age: NON EXISTANT PROPERTY";
}
function CustomGetter(theObj, propertyName)
{
if(theObj.hasproperty(propertyName))
return ToUpperCase(theObj.propertyName);
else
{
return "NON EXISTANT PROPERTY";
}
}
function CustomSetter(theObj, propertyName, value)
{
if(theObj.hasproperty(propertyName))
theObj.propertyName = value + " CUSTOM";
else
{
console.log("NON PROPERTY TO SET");
}
}
感谢你!