Skip to content

Instantly share code, notes, and snippets.

@charlieroberts
Created October 23, 2016 02:07
Show Gist options
  • Select an option

  • Save charlieroberts/81798c2b7ba650664e182c0c4e9ff420 to your computer and use it in GitHub Desktop.

Select an option

Save charlieroberts/81798c2b7ba650664e182c0c4e9ff420 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*.
```js
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.
```js
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()
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment