Skip to content

Instantly share code, notes, and snippets.

@RobbieClarken
Created February 9, 2018 07:44
Show Gist options
  • Save RobbieClarken/b23c3091bd2e8d1f925fa4ee184a137f to your computer and use it in GitHub Desktop.
Save RobbieClarken/b23c3091bd2e8d1f925fa4ee184a137f to your computer and use it in GitHub Desktop.
JavaScript binding demo
/*
To run, save as demo.js in an empty folder and then run:
yarn add babel-cli babel-plugin-transform-class-properties
./node_modules/.bin/babel-node --plugins transform-class-properties demo.js
*/
class Foo {
constructor () {
this.name = 'OK'
this.getName5 = this.getName1.bind(this)
}
getName1 () { return this.name }
getName2 = () => { return this.name }
getName3 = function () { return this.name }
getName4 = function () { return this.name }.bind(this)
}
class Bar {
constructor (foo) {
this.name = 'BAAAAAAAAAAAD'
this.getName1 = foo.getName1
this.getName2 = foo.getName2
this.getName3 = foo.getName3
this.getName4 = foo.getName4
this.getName5 = foo.getName5
}
}
function getName6 () { return this.name }
const getName7 = () => { return this.name }
const foo = new Foo()
const bar = new Bar(foo)
bar.getName6 = getName6
bar.getName7 = getName7
bar.getName8 = getName6.bind(foo)
bar.getName9 = getName7.bind(foo)
console.log('getName1:', bar.getName1())
console.log('getName2:', bar.getName2())
console.log('getName3:', bar.getName3())
console.log('getName4:', bar.getName4())
console.log('getName5:', bar.getName5())
console.log('getName6:', bar.getName6())
console.log('getName7:', bar.getName7())
console.log('getName8:', bar.getName8())
console.log('getName9:', bar.getName9())
@RobbieClarken
Copy link
Author

Output:

getName1: BAAAAAAAAAAAD   
getName2: OK              
getName3: BAAAAAAAAAAAD   
getName4: OK              
getName5: OK              
getName6: BAAAAAAAAAAAD   
getName7: undefined       
getName8: OK              
getName9: undefined

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