所有Javascript对象的通用Getters / Setters?

时间:2017-02-27 14:32:05

标签: javascript getter-setter

是否可以为所有Javascript对象定义通用getter / setter?

我想做的伪代码如下。基本上,人和动物路线 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");
    }
}

谢谢!

3 个答案:

答案 0 :(得分:1)

我最近做了类似的事情。如果在原型上执行defineProperty,则可以将其应用于所有实例。有点像这样:

   Object.defineProperty(Object.prototype, 'test', {
        get: function () {
            return "a test";
        }
    });

var test = new Array(2);
console.log(test); //a test

现在任何对象都有“test”属性。

答案 1 :(得分:0)

您可以使用Object.defineProperty创建属性设置器或getter: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

来自MDN文档:

Object.defineProperty(obj, 'propertyName', {
  get: function() { return bValue; },
  set: function(newValue) { bValue = newValue; },
  enumerable: true,
  configurable: true
});

答案 2 :(得分:0)

您应该使用代理陷阱来执行您想要的操作。

文档:MDN - Proxy handlers

您可以使用类和原型轻松执行该操作,但我更喜欢将自定义处理程序中的getter / setter陷阱用于闭包

通常,它看起来像这样:

var Person = function(profile={})
{
    var required     = ["age", "name", "profession"];
    var buildProfile = function(p)
    {
        for(var prop of required)
        {
            if(!(prop in p))
                throw new ReferenceError
                ("⛔ Missing required property to profile '" +(prop+" in "+JSON.stringify(profile))+ "'");
        }
        return p;
    }(profile);

    var anotherPrivateFunc = function()
    {
        // ...
    };

    var publicMethods = 
    {
        status: function(prop, value)
        {
            // ...
        },
        isAdult: function()
        {
            return this.age >= 18;
        },
    };

    Object.assign(profile, publicMethods);
    return new Proxy(profile,
    {
        get: function(target, prop, receiver)
        {
            if(prop in target)
            {
                switch(prop)
                {
                    case "name":
                        return target[prop].toUpperCase(); break;
                }
            }
            return Reflect.get.apply(Object.getOwnPropertyDescriptor, arguments);
        }
    });
};
var person = new Person({age:32, name: "Water", profession:"developper"})

person.name      // will return WATER
person.age       // --> 32
person.isAdult() // --> true

var person = new Person({age:32}) // will throw an cusotm error
Uncaught ReferenceError: ⛔ Missing required property to profile 'name in {"age":3}'