Last active
June 6, 2021 19:36
-
-
Save akingdom/1d35ce7b953d6bcc1ddd39053ae6e77a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//application/javascript | |
// | |
// Demonstrates callback from a class method | |
// By Andrew Kingdom | |
// MIT license | |
// Define a class | |
let MyClass1 = class { | |
constructor(initialValue) { | |
this.prop = initialValue; // store the parameter value in a property | |
} | |
callback(fn) { | |
let result = fn(); | |
console.log(result); | |
} | |
} | |
// ... and do some things with it... | |
let b = new MyClass1( 1 ).prop; // returns 1 | |
console.log(b); | |
new MyClass1( 2 ).callback(function() {return 'hello';}); // returns "hello" | |
function message() { return 'hi' }; // define a function | |
new MyClass1( 3 ).callback(message); // returns "hi" | |
console.log(this); // returns [object Window] | |
new MyClass1( 4 ).callback(function() {return this;}); // returns [object Window], not the class instance | |
let a = new MyClass1( 5 ); // store an instance of the class | |
a.callback(function() {return this;}); // returns [object Window], not the class instance | |
a.callback(function() {return this.prop;}); // returns undefined -- no property named 'prop' in the Window object | |
a.callback(function() {return a.prop;}); // returns 5 | |
a.prop = 8; // change the property value | |
a.callback(function() {return a.prop;}); // returns 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment