Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Created October 16, 2019 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wtnabe/ec33242432b50ec20b17cf80a39c0fbd to your computer and use it in GitHub Desktop.
Save wtnabe/ec33242432b50ec20b17cf80a39c0fbd to your computer and use it in GitHub Desktop.
const assert = require('assert')
class Klass {
// correct
methodWithCall (val, cb) {
this.val = val
return cb.call(this, val)
}
// who is `this.cb`
methodWithThis (val, cb) {
return this.cb(val)
}
// `this` is undefined
method (val, cb) {
return cb(val)
}
/**
* @param {string} val1
*/
callback (val) {
return this.val === val
}
}
function main () {
const k = new Klass()
assert(k.methodWithCall(1, k.callback))
try {
k.methodWithThis(1, k.callback)
} catch (e) {
assert.strictEqual(e.message, 'this.cb is not a function')
}
try {
k.method(1, k.callback)
} catch (e) {
assert.strictEqual(e.message, 'Cannot read property \'val\' of undefined')
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment