1

I am trying to give a simple example of prototype inheritance in javascript but its not running. Kindly help!

HTML

<script> 
var animal = {eats: 'true'};
animal.prototype.name = "Lion";
console.log(animal);
</script> 
5
  • Please define "not running". Commented Sep 1, 2016 at 9:54
  • Cannot understand what you saying? Commented Sep 1, 2016 at 9:54
  • Haha, what you mean when you say "its not running"? It is running, and firing an error, just check the console. prototype is a property of functions only ... Commented Sep 1, 2016 at 9:55
  • What if I want to add a custom property to an object. Cant I use prototype? Commented Sep 1, 2016 at 9:56
  • 1
    You could use the prototype of the constructor, but it's useful only when adding methods. Please read Working with objects. Commented Sep 1, 2016 at 9:59

3 Answers 3

2

Yes, you can add properties to a prototype... as long as the prototype actually exists. In your case, you have to initialize first the prototype. For example:

var animal = {eats: 'true'};
animal.prototype={};
animal.prototype.name = "Lion";
console.log(animal);

But a nicer way to define a prototype is:

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

// Add new members to the prototype:
Animal.prototype.toString=function()
{
    return "animal "+this.name;
}

// Instance objects:
var a1=new Animal("panther");
console.log(a1.toString());
Sign up to request clarification or add additional context in comments.

Comments

2
var Animal = function() {
  this.eats = 'true';
};

Animal.prototype.name = 'Lion';

var a = new Animal;

console.log(a.name);

Comments

1

Easier way for you. You can use the non constructor way to create objects with existing objects thus using prototypical inheritance in javascript. The other is using functions.

Your animal question has been asked before: Basic JavaScript Prototype and Inheritance Example for Animals , pls follow other javascript protoytype posts here in stackoverflow as there as numerous and enough time has been spent on them. Utilize and be a pro.

var animal = { name: 'Lion'};
var myanimal = Object.create(animal)
myanimal.eats = "true";
console.log(myanimal.name);

3 Comments

meant to use prototypal inheritance.
The above example shows how you can prototypically inherit existing objects without using functions just for a sake of simple example to understand. Long way to go. you can also use functions and classes in ES6
@Peterson Added your animal link

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.