1

In the simplified example below, the MyService.doSomething function has access to someDependency because the prototype function is defined within the MyService constructor.

// Define MyService Class
function MyService(someDependency) {
   MyService.prototype.doSomething = function(){
      return someDependency.doSomething();
   }
}

To use MyService with a given dependency:

// Construct MyService
var myService = new MyService(someDependency);
var result = myService.doSomething();

I am pretty sure that this is bad practice but how do I make the constructor parameter someDependency available to the function?

2 Answers 2

2

First of all, you should initialize the prototype at the same time as when you define the constructor, instead of redefining it every time you create a new instance.

// Define MyService Class
function MyService(someDependency) {
    // ...
}

MyService.prototype.doSomething = function(){
    // ...
}

After that, all that remains to go is to copy the parameters into instance variables explicitly

// Define MyService Class
function MyService(someDependency) {
   this.someDependency = someDependency;
}

MyService.prototype.doSomething = function(){
  return this.someDependency.doSomething();
}

All instance variables are piublic. If you want you can use a naming convention (like starting with an underscore) to mark "pseudo-private" variables.

If you want to use the function parameter directly instead of assigning instance variables you can have the methods be closures belonging to your object instead of a sharred function at the prototype. This lets you use variables from the constructor (and those variables are private!) but makes it harder to create subclasses.

function MyService(someDependency) {
    this.doSomething = function(){
        return someDependency.doSomething();
    };
}

The version with closures can be slower than the prototype version but I wouldn't worry about i most of the time.

Sign up to request clarification or add additional context in comments.

Comments

1

Well, the common way is - if an object has a property, it should actually have that property.

function MyService(someDependency) {
    this.dependency = someDependency; // set it on the object
}

MyService.prototype.doSomething = function(){
   return this.dependency.doSomething(); // now the prototype can access it
}

You're also right in that the way you're currently doing it is bad in at least one sense - the extra closure makes it slower. As for readability - I find it harder to read but that's debatable. It also makes subclassing and extending via prototypical inheritance a lot harder.

Comments

Your Answer

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.