JavaScript is really an interesting language – the more you code / learn it, the better it comes and the more interesting it turns out to be. I will preset a simple way of using prototypes with JS. Pretty much, if you build a prototype function to an object, then you may give this object additional functions. Let’s say that you want to create an object named “Vityata” with the age of 15. (These are the properties). Then you may ask the object to do the following functions – sayIntroduce, sayBye, sayHello with or without additional parameters. Like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!DOCTYPE HTML> <html> <head> </head> <body> <script type="text/javascript"> var Person = function (name,age) { this._name = name; this._age = age; } Person.prototype = { sayHello: function (name) { return ("Hello " + name); }, sayBye: function (name) { return ("Goodbye "+ name); }, sayIntroduce: function(){ return ("My name is " + this._name + " I am " + this._age); }, sayImagine: function () { return ("Imagine all the people ..."); } } var Ivan = new Person('Vityata',15); console.log(Ivan.sayHello("Dolly")); console.log(Ivan.sayBye("John")); console.log(Ivan.sayImagine()); console.log(Ivan.sayIntroduce()); </script> </body> </html> |
This is the result from our code: