0

I am tasked with refactoring some code from a former employee. He uses a constructor function that has two things that seem strange – 1, arbitrary code that runs outside of a function or property, and 2, locally defined functions. This is a simplification of what he is doing:

var Dog = function(){

    // Arbitrary code
    console.log('I am a dog');
    var foo = 'foo';

    // Function defined to local variable
    var bar = function(){
        console.log(foo);
        console.log('bar');
    };

    // Normal function in a constructor
    this.bark = function(){
        console.log('bark');
    };
};

var d = new Dog();

Is there any merit to this style of constructor function? Or would it be better to refactor it to only define functions using this in the style of bark, and then running them on d as needed?

Zachary Nagler
  • 751
  • 1
  • 8
  • 16

1 Answers1

1

Well I don't think there is any special 'merit' is just one in many ways of doing things. The code is simply run on instantiation.

The 'bar' function is hidden from the class user (or 'private' if you like the old OO name), and the 'bark' function can be called from outside the class. It's one of the ways of doing some sort of OO in JS. There are plenty.

Javascript is a very 'free' language. You see people using different ways of doing things all the time. There is not only one 'right' way. Get used to it :)

Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73