Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

If java/C#/etc one might do something like create a constructor with a parameter

ID: 647138 • Letter: I

Question

If java/C#/etc one might do something like create a constructor with a parameter, the parameter being the thing the rest of the object may act upon. How is this done in JavaScript? I'm trying to figure out what the best practice is with JavaScript to do something similar to this C#/Java Object.

public class Blagh{

    public var ThingToActOn; // Appropriate get & set methods here.

    public new Blagh(variable ThingForObjectToActOn) {
        this.ThingToActOn = ThingForObjectToActOn;
    }
}
I was thinking something like this in JavaScript, but it seems maybe I'm missing something. I'm also aware that New in JavaScript is frowned upon for a number of reasons, but am not sure what the best solution is otherwise.

var Symphonize = function(generation_specification){
    this.gen_spec = generation_specification;
}

Symphonize.prototype.act_on_object = function () {

    // Do actions here on the generation_specification value.

    return this.gen_spec;
}

blu = new Symphonize({"gen":"stuff"});

Explanation / Answer

Your solution works, but it breaks encapsulation. You can use the fact that your object is a function to work with local variables instead of properties.

Writing it this way allows you to keep the property private:

function Symphonize(generationSpecification){
this.actOnObject = function(){
// do stuff
return generationSpecification;
}
}

blu = new Symphonize({ gen: "stuff" });
You have to keep in mind, however, that actOnObject will be redefined for every new Symphonize.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote