Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active September 22, 2017 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vielhuber/8fd3c26e52be220f72bc328755c651bd to your computer and use it in GitHub Desktop.
Save vielhuber/8fd3c26e52be220f72bc328755c651bd to your computer and use it in GitHub Desktop.
prototypes / prototypal inheritance #js
// every object has a property called "prototype" where you can add methods and/or other properties to it
// when you create other objects from this object the newly created object will inherit those properties
// without cloning but with referencing
/* newer way */
const cat = {
makeSound: function() {
console.log(this.sound);
}
}
const cat1 = Object.create(cat);
cat1.sound = 'WHOUUUUUU';
cat1.makeSound();
const cat2 = Object.create(cat);
cat2.sound = 'dfhdhjkfkjd';
cat2.makeSound();
// Object.create(cat) creates a new object and sets the prototype of this object to "cat"
console.log( cat.isPrototypeOf(cat2) );
/* old way */
function Cat(sound) {
this.sound = sound;
}
Cat.prototype.makeSound = function() {
console.log('I say: '+this.sound);
}
const cat3 = new Cat('kdfjhkjfdhdkhs');
cat3.makeSound();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment