posts - 19 , comments - 8 , trackbacks - 0

My Links

News

Archives

Post Categories

Image Galleries

  • JavaScript Properties

    Overview

    The following code demonstrates how to use prototype base getters and setters in JavaScript.

    function Colour(red, green, blue, alpha) {
        this.value = [red, green, blue, alpha];
        
    }
    
    Object.defineProperty(Colour.prototype, "red", {
        get: function () {
            return this.value[0];
        },
        set: function (x) {
            this.value[0] = x;
        }
    });
        
    Object.defineProperty(Colour.prototype, "green", {
        get: function () {
            return this.value[1];
        },
        set: function (x) {
            this.value[1] = x;
        }
    });
    
    Object.defineProperty(Colour.prototype, "blue", {
        get: function () {
            return this.value[2];
        },
        set: function (x) {
            this.value[2] = x;
        }
    });
    
    Object.defineProperty(Colour.prototype, "alpha", {
        get: function () {
            return this.value[3];
        },
        set: function (x) {
            this.value[3] = x;
        }
    });
    
    Colour.prototype.toString = function() {
        return "red=" + this.red + ", green=" + this.green + ", blue=" + this.blue + ", alpha=" + this.alpha;
    };
    
    var colour = new Colour(255, 128, 16, 100);
    
    console.log(colour.toString());
    console.log("red=" + colour.red);
    console.log("green=" + colour.green);
    console.log("blue=" + colour.blue);
    console.log("alpha=" + colour.alpha);
    
    colour.red = 0;
    console.log(colour.toString());
    console.log("red=" + colour.red);
    console.log(colour.value);
    

    Print | posted on Wednesday, June 10, 2015 9:21 AM | Filed Under [ JavaScript Property Properties get set getters setters ]

    Feedback

    No comments posted yet.
    Post A Comment
    Title:
    Name:
    Email:
    Comment:
    Verification:
     

Powered by: