すべてのJavascriptオブジェクトに汎用ゲッター/セッターを定義することはできますか?すべてのJavascriptオブジェクト用の汎用ゲッター/セッター?
私がしたいことの擬似コードは以下のとおりです。基本的に、人および動物の道gettersおよびセッター to 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");
}
}
ありがとう! MDN-ドキュメントから https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
:
Object.defineProperty(obj, 'propertyName', {
get: function() { return bValue; },
set: function(newValue) { bValue = newValue; },
enumerable: true,
configurable: true
});
はObject.definePropertyを見てください//開発しますer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty – Psi
オブジェクトのキャッチオールセッター/ゲッターはありません。その機能を得るには、オブジェクトをプロキシでラップする必要があります:http ://stackoverflow.com/questions/7891937/is-it-possible-to-implement-dynamic-getters-setters-in-javascript –