Skip to content

What is the best way to define dependent variables in an object?

In the Google developers recommendation for optimizing JavaScript code, they mention that the best way to declare/initialize new variables for object is to use the prototype. For instance, instead of:

foo.Bar = function() {
    this.prop1_ = 4;
    this.prop2_ = true;
    this.prop3_ = [];
    this.prop4_ = 'blah';
};

Use:

foo.Bar = function() {
    this.prop3_ = [];
};

foo.Bar.prototype.prop1_ = 4;
foo.Bar.prototype.prop2_ = true;
foo.Bar.prototype.prop4_ = 'blah';

However, in my case I have a dependency between variables, for instance:

var appv2 = function(){
    this.start(this.person, this.car); 
}; 

appv2.prototype.toWhom = 'Mohamed'; 
appv2.prototype.person = new person(this.toWhom); 
appv2.prototype.car = new car();

appv2.prototype.start = function(person, car){
    console.log('start for appv2 is called'); 
    person.sayHello('me app v2');
    car.brand();    
}; 

new appv2(); 

Using this.toWhom outside of the main constructor body or a method function of the object will yield undefined. To solve this I could use appv2.prototype.toWhom instead of this.toWhom or I could declare my dependent variables inside of the main constructor body.

But I would like to know what is the best way, in terms of performance, to accomplish this?

Thanks

Answer

To reference toWhom while creating person, you can either store the value in a separate variable:

var toWhom = appv2.prototype.toWhom = 'Mohamed';
appv2.prototype.person = new person(toWhom);

Or, reference it from the prototype, as you suspected:

appv2.prototype.person = new person(appv2.prototype.toWhom);

The reason this.toWhom is undefined is because this doesn’t refer to an instance of appv2 there.