Skip to content

Instantly share code, notes, and snippets.

@benbuckman
Last active December 21, 2015 04:39
Show Gist options
  • Save benbuckman/6251449 to your computer and use it in GitHub Desktop.
Save benbuckman/6251449 to your computer and use it in GitHub Desktop.
Surprising scoping confusion with coffeescript constructors
_ = require 'lodash'
class CrazyParentView
events:
'mousedown .thing': ->
class CrazyChildView extends CrazyParentView
constructor: ->
# debugger
_.extend @events,
'mousedown .child-thing': ->
super
class CrazyCousinView extends CrazyParentView
constructor: ->
# debugger
_.extend @events,
'mousedown .cousin-thing': ->
super
window.kid1 = kid1 = new CrazyChildView
window.kid2 = kid2 = new CrazyCousinView
console.log (kid1.events is kid2.events) # true!!!
console.log (kid2.events is kid1.constructor.prototype.events) # true!!!
backbone = require 'backbone'
_ = require 'lodash'
class CrazyParentView extends backbone.View
events:
'mousedown .thing': ->
# pseudo-constructor,
# backbone (pure JS) constructor calls this for us
initialize: ->
class CrazyChildView extends CrazyParentView
initialize: ->
_.extend @events,
'mousedown .child-thing': ->
super
class CrazyCousinView extends CrazyParentView
initialize: ->
_.extend @events,
'mousedown .cousin-thing': ->
super
window.kid1 = kid1 = new CrazyChildView
window.kid2 = kid2 = new CrazyCousinView
console.log 'events', kid1.events
console.log 'same events?', (kid1.events is kid2.events) # still true!!!
console.log 'same as prototype?', (kid2.events is kid1.constructor.prototype.events) # still true!!!
backbone = require 'backbone'
_ = require 'lodash'
class CrazyParentView extends backbone.View
foo: 1
# pseudo-constructor,
# backbone (pure JS) constructor calls this for us
initialize: ->
class CrazyChildView extends CrazyParentView
initialize: ->
console.log 'child initial foo', @foo
@foo = 2
console.log 'child changed foo', @foo
super
class CrazyCousinView extends CrazyParentView
initialize: ->
console.log 'cousin initial foo', @foo
@foo = 3
console.log 'cousin changed foo', @foo
super
window.kid1 = kid1 = new CrazyChildView
window.kid2 = kid2 = new CrazyCousinView
console.log 'foos', [ kid1.foo, kid2.foo ]
console.log 'same foos?', kid1.foo is kid2.foo
console.log 'kid1 foo same as prototype?', kid1.foo is kid1.constructor.prototype.foo
console.log 'kid2 foo same as prototype?', kid2.foo is kid2.constructor.prototype.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment