Javascript – Object.defineProperty – Eloquent Javascript – Chapter 6

This is the first time I’ve used Object.defineProperty. Below, I’m using it to create a property on an object. The requirement is that the property is a function that is called without parens.

It reveals some interesting things I’ve stumbled across recently. Console.log shows non enumerable properties when called on an object but those properties are not included in a for loop. Why? Because those properties have a property called enumerable that is set to false. If this property should show up in a for loop, include the following when using Object.defineProperty.

If you stumble across this blog, these are my programming notes more than a blog. If you have any comments or questions, feel free to comment.

        enumerable: true

Here’s an example of the code I wrote for the Vector assignment in Chapter 6.

function Vector(x, y) {

    // variables
    this.x = x;
    this.y = y;

    // functions
    this.powUp = function () {
        return Math.pow(this.x, 2) + Math.pow(this.y,2);
    }

    this.plus = function (obj) {
        return new Vector(this.x + obj.x, this.y + obj.y);
    };

    this.minus = function (x, y) {
        return new Vector(this.x - obj.x, this.y - obj.y);
    };

    // requires parens to call / reset value;
    //this.length = function() {
    //  return Math.sqrt(this.powUp())
    //}

    // removes the need for parens / adds code
    // extend the object 1st param
    // give it the name 'length'

    Object.defineProperty (this, 'length', {
        get: function () {
            return  Math.sqrt(this.powUp())
        }
        //set: function () {
        //  return  Math.sqrt(this.powUp())
        //}
    });

    // make it chainable
    return this;
};


// Object.defineProperty Notes:

    Object.defineProperty properties
    get: function() {}        // function to returns value
    set: function() {}        // function to set value
    value: 0,                 // current value
    enumerable: true,         // shows up in for loop
    configurable: true,       // prop can be changed / deleted
    writable: false           // can be modified

    // Can be expressed as an object
    /*
    Object.defineProperties (this, { 
        prop1: { get: function() {}, set: function() {} },
        prop2: { get: function() {}, set: function() {} }
    });
    */

Leave a Reply

Your email address will not be published. Required fields are marked *