0

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"});
asked Jan 3, 2014 at 3:28

1 Answer 1

2

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.

answered Jan 3, 2014 at 13:11
1
  • Exactly what I want actually. I just wanted to make sure it has the "generationSpecification" required. Commented Jan 3, 2014 at 18:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.