Scoping

quick scope test

by mattstyles

JavaScript

console.log( '--- Starting new Run --' )

var scoped = {
  name: 'foo',
  unscoped: function( item ) {
    console.log( this.getName() + item )
  },
  getName: function() {
    return this.name
  },
  unscopedFor: function( list ) {
    for( var i = 0; i < list.length; i++ ) {
      console.log( this.getName() + list[ i ] )
    }
  }
}

var arr = [ 'one', 'two' ]


console.log( '  Try both function unscoped' )
try {
  arr.forEach( scoped.unscoped )
} catch( err ) {
  console.log( 'this.getName should be throwing here' )
  console.error( err )
}

console.log( '  Try exterior function scoped' )
try {
  arr.forEach( scoped.unscoped.bind( scoped ) )
} catch( err ) {
  console.log( 'wont hit this' )
  console.error( err )
}


var lists = [
  [ 'one', 'two' ],
  [ 'foo', 'bar' ]
]

console.log( '  For loop: try both unscoped, with for loop')
try {
  lists.forEach( scoped.unscopedFor )
} catch( err ) {
  console.log( 'this.getName should be throwing here' )
  console.error( err )
}

console.log( '  For loop: try exterior function scoped, with for loop' )
try {
  lists.forEach( scoped.unscopedFor.bind( scoped ) )
} catch( err ) {
  console.log( 'wont hit this' )
  console.error( err )
}