Created
December 7, 2016 08:15
-
-
Save iainplimmer/db0a0c6bef811b83edd436fdf88d3f54 to your computer and use it in GitHub Desktop.
Prototype exploration!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Create an object | |
| function Person(firstname, surname, age) { | |
| this.firstname = firstname; | |
| this.surname = surname; | |
| this.age = age; | |
| this.fullname = function () { | |
| return firstname + ' ' + surname; | |
| } | |
| }; | |
| // Make an instance of the object | |
| var person1 = new Person('Iain', 'Plimmer', 39); | |
| var person2 = new Person('Erin', 'Plimmer', 1); | |
| // Prototype bind a new function to the created object | |
| var frenchname = function () { | |
| return this.surname.toUpperCase() + ' ' + this.firstname; | |
| } | |
| person1.frenchname = frenchname.bind(person1); // Binding using prototype bind | |
| // Add a function to the prototpye for all to inherit | |
| Person.prototype.spanishname = function (newbit) { | |
| return this.firstname + ' ' + newbit + ' ' + this.surname; | |
| } | |
| console.log(person1.spanishname('carlos')); // on prototype, so OK | |
| console.log(person2.spanishname('alicia')); // on prototype, so OK | |
| console.log(person1.frenchname()); // OK | |
| console.log(person2.frenchname()); // undefined as its on the object not the prototype |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment