Skip to content

Instantly share code, notes, and snippets.

@kaizer1v
Last active November 14, 2018 17:40
Show Gist options
  • Save kaizer1v/957c542fbd9f3f285c74ce875f976562 to your computer and use it in GitHub Desktop.
Save kaizer1v/957c542fbd9f3f285c74ce875f976562 to your computer and use it in GitHub Desktop.
Emulate Prototype Inheritance
/* ===============
* This snippet shows you how to inherit from one object into another,
* without using the `new` keyword or using any functions.
* ===============
*/
// create a class object which we will use to emulate inheritance
var Person = {
firstname: 'John',
lastname: 'Doe'
}
// explicitely provide a propertyname called `prototype` and make it an object
Person.prototype = {}
// add a method to the prototype
Person.prototype.sayname = function() {
return `${this.firstname} ${this.lastname}`
}
// now, treat `Person` as a class, and let's make an instance of `Person`
// but since, `Person` is actually an object, we cannot use the `new`
// operator to make an instance of it. So ...
var p1 = {} // create an empty object
// add some new values to the properties already provided
p1['firstname'] = 'Auto'
p1['lastname'] = 'Matic'
// we know that every object created with a `new` keyword
// has a `__proto__` property which pionts to the constructor's
// prototype. So, let's emulate that here...
p1.__proto__ = Person.prototype // <--------------- INHERITANCE
console.log(p1.sayname()) // Auto Matic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment