DEV Community

RocketMaker69
RocketMaker69

Posted on

Using Object.defineProperties()

Hello, today we will learn how to use Object.defineProperties(/* object */, {
// properties here...
})
, which has the following arguments:
object (1st arg): The object to define the properties to.

props: The properties to add add to the object.

Here's an example:

let object = { };

Object.defineProperties(object, {
  a: { value: 4 }
});

console.log(object.a);   // 4
Enter fullscreen mode Exit fullscreen mode

To begin, we pass object as the first argument, so we will add properties to object. Then, we pass an object (the same as a Python Dictionary) as the second argument. You see that every key will be added to the object object. The key bar has another key, value, which is 4. So, it's the same thing as this:

let object = { };

object.a = 4;
Enter fullscreen mode Exit fullscreen mode

But Object.defineProperties() supports adding multiple properties! Remember the interpreter written in JavaScript in the Making an interpreter in Python post? Here's a newer variant:

let i = { };

Object.defineProperties(i, {
  stack: { value: [ ] },
  code : { value: null },
  init : {
    value: function (c) {
      this.i = c.i;
      this.d = c.d;
  }},
  run: {
    value: function () {
      for (let step in this.i) {
        switch (step[0]) {
          case "load": this.stack.push(eval(step[1]));
          case "add":
            let b = this.stack.pop();
            let a = this.stack.pop(); 
            this.run(["load", a+b]);
          case "dump": 
            if (!step[1]) console.log(this.stack.pop());
            else console.log(eval(step[1]));
        }
      }
  }}
});
Enter fullscreen mode Exit fullscreen mode

With this, goodbye and have a good day!

Top comments (0)