Isaac
Isaac

Reputation: 12874

Why prototype consider in object but not in function instead

From this MDN, it made the appearance that prototype is a property of Object, however it seems more like prototype is a property of function instead?

Given the below code it's hitting TypeReference

let Animal = {
  name: 'randomAnimal'
}

Animal.prototype.speak = function () {
  console.log(this.name + ' makes a noise.');
}

In order to make it work, instead of object, we change it to function instead as below

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

Animal.prototype.speak = function () {
  console.log(this.name + ' makes a noise.');
}

My question is more on try to understand the morale or reason behind why saying prototype is consider property of object, although one can argue that all functions are objects

Upvotes: 1

Views: 67

Answers (1)

teroi
teroi

Reputation: 1087

Prototype is an object property and functions are first class objects.

To make an object parameterizable during instantiation, we can create an object by means of a constructor function which is as you wrote:

function Animal (name) {
    this.name = name;  
}
Animal.prototype.speak = function() {
    console.log(this.name + " says hi!");
}
var lion = new Animal("lion");
lion.speak(); // "lion says hi!"

Here a name is given at the object construction.

But you can create objects also by using object initializers, like

let lion = { 
    name: "lion",
    speak: function() {
        console.log(this.name + " says hi!");
    }
}
lion.speak(); // "lion says hi!"

Naturally it is easier with a constructor, especially if you have several properties to initialize and/or several similar objects to construct.

Third way to create objects is to use Object.create(). It allows you to specify the prototype object on object creation, like:

var cat = Object.create(lion);
cat.name = "house cat";
cat.speak(); // "house cat says hi!"
console.log(lion.isPrototypeOf(cat)); // true

For info about objects in JavaScript, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Edit: But by default all functions have a "prototype" member object as we don't know if the function is to be used as a constructor. Object literals or objects created with Object.create() won't have it.

console.log(cat.prototype); //undefined

As for adding prototype member object to an object literal, a stack overflow question: Adding a prototype to an object literal

Upvotes: 2

Related Questions