Skip to content

Instantly share code, notes, and snippets.

@PavelVanecek
Last active September 18, 2015 11:09
Show Gist options
  • Save PavelVanecek/b01ac50935f92a2e19bb to your computer and use it in GitHub Desktop.
Save PavelVanecek/b01ac50935f92a2e19bb to your computer and use it in GitHub Desktop.
suite 'Constructor binding', ->
ConstructorFn = null
boundFn = null
spy = null
teardown ->
# cleanup global state after any failed tests
delete global.instanceProperty
setup ->
ConstructorFn = (param) ->
this.instanceProperty = param
return
boundFn = ConstructorFn.bind null, 'foo'
console.log 'boundFn name', boundFn.name, ConstructorFn.name
suite 'with new', ->
result = null
setup ->
result = new boundFn()
test 'should return object', ->
assert.isObject result
test 'should produce correct instance', ->
assert.instanceOf result, ConstructorFn
test 'should not pollute global namespace', ->
assert.notProperty global, 'instanceProperty'
test 'should set correct instanceProperty', ->
assert.equal result.instanceProperty, 'foo'
suite 'without new', ->
result = null
setup ->
result = boundFn()
test 'should return undefined', ->
assert.isUndefined result
test 'should pollute global namespace', ->
assert.property global, 'instanceProperty'
@PavelVanecek
Copy link
Author

This example test suite confirms the behaviour documented on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

The [first .bind() parameter] value is ignored if the bound function is constructed using the new operator.

A bound function may also be constructed using the new operator: doing so acts as though the target function had instead been constructed. The provided this value is ignored, while prepended arguments are provided to the emulated function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment