0

I am instantiating an object in javascript using a constructor. Like so:

var Constructor = function(){
    this.property1 = "1";    
}
var child = new Constructor();
console.log(child) // Constructor {property1: "1"}

I would like a method to be invoked once whenever a child object is instantiated via the new keyword. I would like this method to only be available to the Constructor.

This is what I have come up with so far:

var Constructor = function(property2){
    this.property1 = "1";
    (function(){ this.property2 = property2}).call(this);
}
var child = new Constructor("2")
console.log(child) // Constructor {property1: "1", property2: "2"}

Is this the correct way to approach this problem in Javascript? Is there a cleaner or more robust way that I could approach this problem?

2
  • 3
    I assume the actual function you want to call is defined somewhere else? Because as it is, it would be much cleaner to simply inline this.property2 = "2";. Are you asking whether f.call(this) is the correct way of calling a function and setting this to a specific value? If yes, then yes. Commented Dec 30, 2016 at 1:20
  • @FelixKling I am just using that function as an example, I would replace that code with other functionality that would mutate the object based upon parameters entering the Constructor function. I will edit the question to reflect this Commented Dec 30, 2016 at 1:26

1 Answer 1

1

What you are doing seems kind of useless because you could directly use

var Constructor = function(property2) {
  this.property1 = "1";
  this.property2 = property2;
};

But if your constructor does complex things and what you want is splitting them into parts for better abstraction, then personally I would take these parts outside in order to have a cleaner constructor:

var Constructor = (function() {
  function someLogic(instance, value) {
    instance.property2 = value;
  }
  return function Constructor(property2) {
    this.property1 = "1";
    someLogic(this, property2);
  };
})();
Sign up to request clarification or add additional context in comments.

4 Comments

I have edited my question to reflect that my constructor would be doing more complex things. Thank you
No you haven't made it clear in any edit that the function would be any more complex
@GerardSimpson The only edit you made was to add a parameter to the constructor. What does that have to do with the complex function you want to call?
If you can abstract the idea that the function is doing more than setting a simple variable, you will be able to get to the crux of the issue. Thanks

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.