Skip to content

Instantly share code, notes, and snippets.

@steelywing
Last active August 29, 2015 14:01
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 steelywing/c37de612e535dada4454 to your computer and use it in GitHub Desktop.
Save steelywing/c37de612e535dada4454 to your computer and use it in GitHub Desktop.
javascript class explain
function Class() {}

actually

Class.prototype = new Object();
Class.prototype.constructor = Class;

var instance = new Class();

actually

var instance = new Object();
instance.__proto__ = Class.prototype
Class.call(instance);

function BaseClass() {}
function Class() {}
Class.prototype = new BaseClass()

// true, because `new Class().__proto__ === Class.prototype`
new Class() instanceof Class
// true, because `new Class().__proto__.__proto__ === BaseClass.prototype`
new Class() instanceof BaseClass

Class.prototype.constructor === BaseClass
// we should better set constructor back to Class
Class.prototype.constructor = Class

The Class.prototype.constructor property makes no practical difference internally. It's only difference when our code explicitly uses it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment