Prototype attribute where is it defined?

Tell us what’s happening:

This works, but my question is why is prototype attribute defined outside of the object or constructor? Where would this go in code i.e. within the class or in the code after the instance of the object is created?

Your code so far


function Dog(name) {
  this.name = name;
}

Dog.prototype.numLegs = 4;

let beagle = new Dog("Snoopy");

let ownProps = [];
let prototypeProps = [];

// Add your code below this line 

for (let property in beagle){
  if(beagle.hasOwnProperty(property))
  {
    ownProps.push(property);

  }
  else{
    prototypeProps.push(property);
  }
}
console.log(ownProps);
console.log(prototypeProps);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties

It’s defined outside of the constructor because constructor is generally used for setting up properties whose values are going to be different for different objects (e.g. name). On the other hand, prototype is used to put properties that are meant to be shared by all objects created with that constructor function.

So going with this example, suppose I want my dogs to have a bark method. I could define it in the constructor, but then each instance of dog would have its own separate copy of bark, taking up space unnecessarily. Instead, it would be better to put it on constructor’s prototype. That way, there’d only be one single bark method, accessible by all dog objects. Much more efficient.

As far as where it goes in the code, it doesn’t really matter as far as I know. You can modify constructor’s prototype property at any point, and all objects that you made with that constructor will have access to it.

ES6 adds a different syntax to make constructors and modify their prototype, and it’s called the class syntax. It’s more similar to other OOP languages. Here’s what this dog example would look like:

class Dog {
    constructor(name) {
        this.name = name;
    }

    numLegs = 4;

    bark() {
        console.log('Woof woof');
    }
}
1 Like

Yes, this is much simpler.