简体   繁体   中英

Validate/Preprocess property before assigning it to object in JavaScript

What is the best-practice to validate and/or preprocess a property before assigning it to an object in JavaScript?

The application for that would be to create an object and to guarantee that a specific property of it will always have a specific type or maybe do some preprocessing with it.

For example, if I create an object:

var obj = {
    settings: {}
};

Then when I do something like:

obj.settings = "{foo: bar}";

It would automatically check the type of the assignment - if it is a string, it will try to parse it to an object; if it's an object, it will just assign it; else it will throw an error. This would protect the object's property against being assigned to "anything".

Also, does this make sense at all to do in JavaScript or am I just trying to have strong typed features in a language that is weak typed?

You can do this with Object.defineProperty :

var obj = {}
Object.defineProperty(obj, 'settings', {
  set: function (x) {
    if (typeof x === 'string') {
      this._settings = JSON.parse(x)
    } else {
      this._settings = x
    }
  },
  get: function () {
    return this._settings
  }
})

obj.settings = {foo: 'bar'}
console.log(obj.settings)
obj.settings = '{foo: "baz"}'
console.log(obj.settings)

However, if this is desirable depends on your specific use case. I frankly never used it so far. My recommendation is: don't get fancy :)

IMHO this is not strong typing, but the opposite as you are more dynamic. If you want strong typing you could try flow or TypeScript

A simple solution could be to use a getter/setter like below that gets triggered if a value is assigned to a property and how to process it :

let obj = {}
Object.defineProperty(obj, "settings", {
 set: function (value) { // preprocess
    this._value = value;
 },
 get: function () {
    return "changed";
}
});

You could do this afterward:

    obj.settings = "{foo: bar}";

Let me know if this makes any sense.

Reference: MDN Reference: Object.defineProperty()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM