Skip to content

Instantly share code, notes, and snippets.

@iainplimmer
Created December 7, 2016 08:15
Show Gist options
  • Select an option

  • Save iainplimmer/db0a0c6bef811b83edd436fdf88d3f54 to your computer and use it in GitHub Desktop.

Select an option

Save iainplimmer/db0a0c6bef811b83edd436fdf88d3f54 to your computer and use it in GitHub Desktop.
Prototype exploration!
// 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