Skip to content

Instantly share code, notes, and snippets.

@charlieroberts
Last active October 23, 2016 02:09
Show Gist options
  • Save charlieroberts/8c97b6244b10c59c95bf3e99c25e3f89 to your computer and use it in GitHub Desktop.
Save charlieroberts/8c97b6244b10c59c95bf3e99c25e3f89 to your computer and use it in GitHub Desktop.

Prototype inheritance

Simply put, prototypical inheritance means that any object can delegate property lookups and method calls to any other object. Prototypical inheritance is also used in Lua, AppleScript, and many other languages have add-ons / extensions to support it. It was first used in the language Self.

var a = { test: function() { console.log( 'I am testing' ) } }

// create a new object with an argument prototype
var b = Object.create( a )

b.name = 'I am b'
b.test() // => 'I am testing'

var c = Object.create( b )
console.log( c.name ) // => 'I am b'

// if we assign an object its own property, the JS runtime will no longer
// look to that objects prototype to find that property
c.name = 'I am c' 
console.log( c.name ) // => 'I am c'

// b.name remains the same
console.log( b.name ) // => 'I am b'

Functional scoping

Given a function foo, variables created within foo are recognized anywhere within foo, including insides other functions that are created within foo. If a variable is not created inside of a function it becomes a global, and part of the window object in the browser. The JS runtime will first look for variables declared inside the currently executing function (foo), and then it will move up one level and check for variables declared inside the function that called foo, and it will continue working its way up until it reaches the global namespace.

var foo = function() {
  var bar = true,
      test = 2
  
  var baz = function() {
    var test = 5
    console.log( 'does baz know about bar?', bar )
    console.log( 'what does baz think the value of test is?', test )
  }
  
  console.log( 'what does foo think the value of test is?', test )
  
  baz()
} 

foo()
// => 'what does foo think the value of test is? 2
// => 'does baz know about bar? true'
// => 'what does baz think the value of test is? 5'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment