Created
October 16, 2019 01:11
-
-
Save wtnabe/ec33242432b50ec20b17cf80a39c0fbd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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