Skip to content

Instantly share code, notes, and snippets.

@lcustodio
Created September 4, 2015 20:06
Show Gist options
  • Save lcustodio/a718218c6e7192d2a953 to your computer and use it in GitHub Desktop.
Save lcustodio/a718218c6e7192d2a953 to your computer and use it in GitHub Desktop.
Simple explanation between classes, prototypes and properties in javascript
//Class
function MyClass() {
this.ownMember = 123;
}
//Prototype declaration
MyClass.prototype = {
prototypeMember: 456
};
//Instantiation
var myObject = new MyClass();
//Instance has an own member 'ownMember'
myObject.hasOwnProperty('ownMember') === true;
myObject.ownMember;
//However the instance doesn't have the own member 'prototypeMember'
myObject.hasOwnProperty('prototypeMember') === false;
myObject.prototypeMember;
//The function MyClass may have another properties
MyClass.staticMember = 789;
//However the instance won't have this property
myObject.staticMember === undefined;
//In order to create a proper inheritance, sub class can call the parent constructor
function MySubClass () {
MyClass.apply(this, arguments);
}
//And should receive the prototype as well
MySubClass.prototype = new MyClass();
//However the subclass, still doesn't have a reference to 'staticMember' property
MySubClass.staticMember === undefined;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment