Created
August 13, 2015 07:54
-
-
Save shaunwallace/ef39a7fc48ce76e7cfa5 to your computer and use it in GitHub Desktop.
Prototypes in Javascript
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
var person = { kind : ‘person’ }; | |
var shaun = Object.create(person); | |
person.isPrototypeOf(shaun); // true | |
person.kind // 'person' | |
shaun.kind // 'person' | |
shaun.sayHello = function(){ console.log(‘Hello’) }; | |
// since the object shaun's prototype points to person, then person // will not inherit from the person object but any further objects // created via Object.create(shaun) will have access to this method | |
person.sayHello(); // UncaughtTypeError | |
var cloneShaun = Object.create(shaun); | |
cloneShaun.prototype // undefined | |
shaun.isPrototypeOf(cloneShaun); // true | |
shaun.hasOwnProperty('sayHello'); // true | |
// define People using a constructor function | |
function People(peeps) { this.people = peeps; }; | |
// create an instance of People | |
var group = new People([‘person_1’, person_2’]); | |
group.people; // [‘person_1’, person_2’] | |
// Every instance that was created via the constructor function | |
// will now have this property available | |
People.prototype.getPeople = function() { return this.people; }; | |
group.getPeople(); // [‘person_1’, person_2’] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment