Javascript Classes: Constructor parameters become private properties!

Sometimes I do experiments while I learn. Today I was learning making private properties in Javascript objects and I made a hack to declare and initialize private properties in a single line of code. I started with this code:

function StudentReport() {
    var grade1 = 4;
    var grade2 = 2;
    var grade3 = 1;
    this.getGPA = function() {
        return (grade1 + grade2 + grade3) / 3;
    };
}

var myStudentReport = new StudentReport();


console.log("Your overall GPA is " + myStudentReport.getGPA());

Then I wanted to pass values for private properties in the constructor. So I modified the class definition by this:

function StudentReport(grade1, grade2, grade3) {
    var grade1 = grade1;
    var grade2 = grade2;
    var grade3 = grade3;
    this.getGPA = function() {
        return (grade1 + grade2 + grade3) / 3;
    };
}

var myStudentReport = new StudentReport(4,2,1);

It works! Why should it work? Defining a variable after using that works, which supports javascript variable “Hoisting”. So the input parameters are actually initialized as private properties. So, I dared to try this:

function StudentReport(grade1, grade2, grade3) {
    this.getGPA = function() {
        return (grade1 + grade2 + grade3) / 3;
    };
}

var myStudentReport = new StudentReport(4,2,1);


console.log("Your overall GPA is " + myStudentReport.getGPA());

It works. So, any local variable used in the object or class scope becomes a private property! You don’t even need to declare them! One line of constructor parameter can both define and initialize private properties in javascript. Btw, don’t do that because I don’t know if the future versions of javascript would support that because this type of parameters increases memory needed for objects as they remains as properties now.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s