Skip to content

Instantly share code, notes, and snippets.

@laustdeleuran
Created May 30, 2012 08:59
Show Gist options
  • Save laustdeleuran/2834743 to your computer and use it in GitHub Desktop.
Save laustdeleuran/2834743 to your computer and use it in GitHub Desktop.
Function expressions vs Function declarations
// This is a function declaration
function foo(){};
// This is a function expression
var foo = function(){};
// Hoisting in practice
bar(); // Returns "bar", because function is hoisted into beginning of scope
function bar(){
return "bar";
};
bar(); // Still returns "bar"
foo(); // Casts TypeError: undefined is not a function, because the var is hoisted as undefined, but the function isn't.
var foo = function(){
return "foo";
};
foo(); // Returns "foo"
var Foo = function(){};
function Bar(){};
var instanceOfFoo = new Foo();
var instanceOfBar = new Bar();
instanceOfFoo.constructor.name; // Returns nothing
instanceOfBar.constructor.name; // Returns "Bar"
// Solution
var Fubar = function Fubar(){};
var instanceOfFubar = new Fubar();
instanceOfFubar.constructor.name; // Returns "Fubar", but beware, might behave unexpectedly in IE<9 - see http://kangax.github.com/nfe/
// Naming and inheritance - corrected!
// Base class
var BaseClass = function BaseClass(){
return this;
};
// Sub class - inherits from BaseClass
var SubClass = function SubClass(){
return BaseClass.apply(this, arguments); // Use base class constructor
};
SubClass.prototype = new BaseClass(); // This ensures the inheritance
SubClass.prototype.constructor = SubClass; // This corrects the constructor pointer because it points to BaseClass - https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript#Inheritance
// Instantiate
var instanceSub = new SubClass();
// Get name
instanceSub.constructor.name // Returns "SubClass" - YAY!
// Naming and inheritance
// Base class
var BaseClass = function BaseClass(){
return this;
};
// Sub class - inherits from BaseClass
var SubClass = function SubClass(){
return BaseClass.apply(this, arguments); // Use base class constructor
};
SubClass.prototype = new BaseClass(); // This ensures the inheritance
// Instantiate
var instanceSub = new SubClass();
// Get name
instanceSub.constructor.name // Returns "BaseClass" - WTF?!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment