I found this example in w3school related to topic "Prototype" in js. My question is that we can do the same with creating simple function then what is the importance of prototype. Can anyone explain.Thanx in advance.
<button type="button" onclick="doSomething()">Click Me</button>
function doSomething(){
var fruits=["apple","banana","papaya"]
console.log(fruits)
fruits.uCase()
console.log(fruits)
}
Array.prototype.uCase=function(){
for(var i=0;i<this.length;i++){
this[i]=this[i].toUpperCase();
}
}
You should not alter built in prototype which you are doing in this case for Array(build in Array of JS).
Now whats use of prototype : Let's say you want to define common method for all objects(instances) to Function. Then its been used.
Example : In memory wise its shared to all instances of function constructor
function person(name) {
this.name = name;
}
person.prototype.printName = function() {
console.log("hello " + this.name);
}
var obj1 = new person("vips");
var obj2 = new person("bips");
obj1.printName();
obj2.printName();