and I would like to know the below syntax is correct?
cat c = new animal;
No, JavaScript variables are always loosely typed, so you don't declare types for them, you just declare them with var
(and in ES6, let
).
So:
var c = new animal;
Side note #1: In JavaScript, the overwhelming convention is to use an initial capital letter for functions that are intended to be used as constructor functions (e.g., via the new
keyword). E.g., Animal
and Cat
, not animal
and cat
.
Side note #2: About this:
// I know this syntax and works well
cat.prototype= new animal;
That's a common, but poor, practice. Here's how to do that correctly:
cat.prototype = Object.create(animal.prototype);
cat.prototype.constructor = cat;
...and then in cat
, as the first thing:
animal.call(this);
Complete example with updated capitalization:
function Animal() {
}
function Cat() {
Animal.call(this);
// ...add Cat-level initialization here
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
About Object.create
: It's an ES5 function that creates an object with a specific underlying prototype. The proper ES5 version takes two arguments, and what it does with the second argument cannot be shimmed on older browsers. But for what we're doing, we only need the first argument, which can be shimmed on older browsers:
if (!Object.create) {
Object.create = function(proto, props) {
if (typeof props !== "undefined") {
throw "Object.create shims cannot implement the second argument.";
}
function ctor() { }
ctor.prototype = proto;
return new ctor();
};
}
So why is Cat.prototype = new Animal;
poor practice? Well, what if Animal
takes per-instance arguments? Consider:
function Animal(age) {
this.age = age;
}
What would we give for age
in the Cat.prototype = new Animal(???);
line?
Answer: We don't. We shouldn't call Animal
, which is a constructor function for instances, until we're constructing an instance. Instead, we create a new object for the Cat.prototype
property, and give that new object Animal.prototype
as its prototype.
Complete example:
function Animal(age) {
this.age = age;
}
function Cat(age, color) {
Animal.call(this, age);
this.color = color;
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
var c = new Cat(14, "Tabby");