Reputation: 8240
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>
Upvotes: 1
Views: 128
Reputation: 656
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);
Upvotes: 1
Reputation: 906
var Animal = function() {
this.eats = 'true';
};
Animal.prototype.name = 'Lion';
var a = new Animal;
console.log(a.name);
Upvotes: 2
Reputation: 8783
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());
Upvotes: 2