0

What are usages of "prototype" properties in javascript

prototype in javascript

2nd Feb 2018, 11:17 AM
Ganesh Nandyala
Ganesh Nandyala - avatar
4 Respostas
+ 1
All instances of a type have all prototype methods defined. 'this' holds the value of the current instance. Number.prototype.squared=function() { return this**2; } var a = 4; // 4 is an instance of Number a.squared(); // 16 // Also works with instances generated by the 'new' keyword var a = function(string) { this.string = string; } a.prototype.getString=function() { return this.string; } b = new a("abc"); alert(b.getString()); // abc
2nd Feb 2018, 11:24 AM
Draphar
+ 1
thank you Draphar. so prototype is used to add additional properties to the object or function. can we modify the property using prototype.
2nd Feb 2018, 11:32 AM
Ganesh Nandyala
Ganesh Nandyala - avatar
0
Sorry, the direct manipulation of the value is not possible, only for native methods like .reverse() for arrays. I can't say String.prototype.change = function (number){ this = number; // 'Invalid left-hand sign in assignment', which means 'can not change the value on the left' } "abc".change(1); But you can return new values String.prototype.add = function (number){ return parseInt(this) + number; } "3".add(4); // 7
2nd Feb 2018, 11:55 AM
Draphar
0
thank you Draphar
2nd Feb 2018, 2:52 PM
Ganesh Nandyala
Ganesh Nandyala - avatar