6

Please provide your thoughts with respect to Javascript only! I am aware of classes and classical inheritance but not at a great detail.

As far as I know, constructors are used as prototypes for other objects. For example, I could create a car constructor and give it objects such as hondaCivic, toyotaCamry, etc. Are there any other important things I should know about constructors?

Furthermore,

  1. What is the purpose of a constructor, apart from what I have already stated?
  2. What are the benefits / disadvantages of a constructor?
0

3 Answers 3

6

A constructor is just a normal function. There is nothing special about it inherently.

All functions have a property called prototype.

If you write

var myInstance = new MyFuction();

JavaScript does something special with your function when it executes it.

It sets the value of this inside the function body to be myInstance. Additionally, it creates a reference to MyFunction.prototype and stores it as an internal property of myInstance.

When your code is executing, the rule that the interpreter follows is such that, if you try to access a property on myInstance that it can't find, it will follow that reference to the function's prototype and look there. This forms a chain, known as the prototype chain that leads all the way up to Object.prototype.

Here's an example:

function Dog(name, breed) {
  this.name = name;
  this.breed = breed;

  //if you don't specify a return value, `this` will be returned
}

Dog.prototype.speak = function() {
  alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
}

var myDog = new Dog('buttercup', 'poodle');
myDog.speak();

The snippet above works, but if you run: console.log(myDog) you'll see that it does not have a speak method. the speak method was found in it's prototype.

This means that all 'instances' of Dog that are created will all share the same speak method.

So, If I create another dog, it will be able to speak aswell:

var tommysDog = new Dog('rosco', 'pitbull');
tommysDog.speak(); //tommy's dog can speak too

  
    function Dog(name, breed) {
      this.name = name;
      this.breed = breed;

      //if you don't specify a return value, `this` will be returned
    }

    Dog.prototype.speak = function() {
      alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
    }

    var myDog = new Dog('buttercup', 'poodle');

    var tommysDog = new Dog('rosco', 'pitbull');
    tommysDog.speak();

It also means that if I change the value of Dog.prototype.speak at run time, all instances will be affected.


Note: technically, functions do have a constructor property but it's not that important and it would just confuse you more if I tried to explain it here.

I suggest you read the mozilla docs

Additionally, I suggest you read this book. You'll learn a lot about proper design.


Also note that this is just one way to achieve code re-use. You don't have to go through prototypes at all. In fact JavaScript has methods that let you supply arbitrary values as the value of this to functions as an argument.

This means that, even though my pet lizard can't normally speak, I can just borrow the method from Dog.prototype by utilizing a method like call() or apply(). (All functions have these methods because they 'inherit' them from Function.prototype.)

function Dog(name, breed) {
  this.name = name;
  this.breed = breed;

  //if you don't specify a return value, `this` will be returned
}
Dog.prototype.speak = function() {
  alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
};



function Lizard(name, species) {
  this.name = name;
  this.species = species;
}

Lizard.prototype.speak = function() {
  var pretend_dog = { name: this.name, breed: this.species };
  Dog.prototype.speak.call(pretend_dog);
};

var myLizard = new Lizard('larry', 'chamelion');
myLizard.speak();

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

Comments

4

A "constructor" in Javascript is just a function which has a special property called "prototype". Most (but not all) built-in and all user-defined functions are also constructors. When you define a function, like

function Car() {}

you actually create two objects: a function and its prototype, which is an empty object by default:

enter image description here

The only difference between a constructor and a "non-constructor" function is that the former can be used in a new expression:

honda = new Car()

The new expression does three things:

  • allocate a new generic object
  • copy the constructor's prototype into this object's internal __proto__ property
  • execute the constructor body, passing the newly created object as this

This final object relationship looks like this:

enter image description here

Constructors start making sense when you redefine their default prototype, thus creating a prototypical inheritance chain:

function Vehicle() {}

function Car() {}

Car.prototype = new Vehicle;

honda = new Car;

Now honda inherits from Car.prototype which in turn inherits from Vehicle.prototype:

enter image description here

5 Comments

Wow. Thanks a lot for such an elaborate post with images. I do have a question about the prototype property. What does the prototype property do? What effect does it have? Why is it good to have the prototype property carried over? Furthermore, what do you mean by "allocate a new generic object"? Do you mean that it allocates memory for a new empty object? Thanks
@user3170033: if you have a function like myFunc, and use it as a constructor myObj = new myFunc, then myObj.__proto__ becomes equal to myFunc.prototype.
When we have myFunc.prototype, why is it so special? What's the benefit? Why would we want myFunc.prototype?
@user3170033: func.prototype is one way to establish object inheritance in js, another being Object.create.
Sorry for potentially necroing, but shouldn't the second prototype's constructor also point to the Vehicle function in the last image?
0

constructors are used as prototypes for other objects.

No, they are not - if you mean "inheritance target" by the term "prototype".

For example, I could create a car constructor and give it objects such as hondaCivic, toyotaCamry, etc.

Not sure what you mean. Please show code if you have questions about it.

What is the purpose of a constructor?

Not different from other languages, the purpose of a constructor function is to initialise an instance.
In JS, you can call it with the new operator to create instances (objects).

What are the benefits / disadvantages of a constructor?

It does its job. Sometimes, its the wrong tool used for the job.

4 Comments

Thanks Bergi. Currently, I am doing the constructor exercises on codecademy and they quoted: "But this approach of adding in properties one at a time for every object is tedious! Instead of always using the boring Object constructor, we can make our own constructors. This way we can set the properties for an object right when it is created. So instead of using the Object constructor which is empty and has no properties, we can make our own constructors which have properties." This shows that a constructor is used as a prototype for other objects, doesn't it?
I think they meant "we can write our own constructors that create properties (when it is used to create an object)" (as opposed to new Object() which creates empty objects).
So you can write constructors that create objects after a "template", by giving it the properties that you want, yes. The term "prototype" is used for something very different in JavaScript, though. This might be just a terminology problem?
An important difference is that you don't give the properties to the constructor (which itself is an object of type Function), but you are giving the properties to the object (instance) that the constructor creates.

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.