是否可以爲所有Javascript對象定義泛型getter/setters?適用於所有Javascript對象的通用Getters/Setters?
我想要做的僞代碼如下。基本上,人和動物路線獲取者和設置者到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");
}
}
謝謝!
看一看Object.defineProperty:https://開頭開發er.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty – Psi
對象沒有全面的setter/getter,你需要將你的對象包裝在Proxy中才能獲得這個功能:http ://stackoverflow.com/questions/7891937/is-it-possible-to-implement-dynamic-getters-setters-in-javascript –