Javascript Prototype to Class
Prototype
/**
* Leve 0
*/
function Animal(name){
let obj = {};
obj.name = name;
obj.myName = function(){
console.log(obj.name)
}
return obj
}
let dog = Animal('puppy'); // --> Actually its creating own obj so memory will losss will happen
let cat = Animal('cat1'); // its creating multiple obj for each animals
console.log(dog.name);
console.log(dog.myName());
/**
* Leve 1
*/
function Animal(name) {
let obj = Object.create(Animal.prototype);
obj.name = name;
return obj;
}
Animal.prototype.myName = function () {
console.log(this.name)
};
let dog = Animal('puppy'); // --> Actually its refering global obj for myName
console.log(dog.name); // So that memory won't get loss
console.log(dog.myName());
/**
* Leve 2
*/
function Animal(name) {
this.name = name;
}
Animal.prototype.myName = function () {
console.log(this.name)
};
let dog = new Animal('puppy'); // --> Actually its refering global obj for myName using "Javascript internal Prperty 'new' "
console.log(dog.name);
console.log(dog.myName());
/**
* Leve 3
* Moden tech for Class to avaoid prototype concept
*/
class Animal{
constructor(name){
this.name = name;
}
myName(){
console.log(this.name);
}
}
let cat = new Animal('cat');
console.log(cat.name);
console.log(cat.myName());
Comments
Post a Comment