Last active
January 6, 2016 22:08
-
-
Save MikeDigitize/523ef2adc25f8c963af3 to your computer and use it in GitHub Desktop.
Helpers for beginners to JavaScript at AO.com
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
// a function returning `something` in javascript is a useful tool | |
function foo() { | |
return "foo"; | |
} | |
// create a reference | |
var bar; | |
// if we assign `bar` to `foo` | |
bar = foo; | |
// bar now just points to the same function as foo | |
bar === foo; // true | |
// we need to assign `bar` to the call of `foo` | |
bar = foo(); | |
// `bar` is now assigned to the return value of `foo` | |
bar; // "foo" | |
// functions can return objects | |
function foo() { | |
return { | |
bar : function() { | |
return "foo"; | |
} | |
} | |
} | |
var bar = foo(); | |
// `bar` is now the object returned from `foo` | |
bar.bar(); // "foo" | |
// functions can return functions | |
function foo() { | |
return function() { | |
return "bar"; | |
} | |
}; | |
var bar = foo(); | |
bar(); // "bar" | |
// when a function returns, its return value can immediately be operated on | |
// from all the above examples | |
function foo() { | |
return "foo"; | |
} | |
// operate immediately on the returned string | |
var bar = foo().length; // 3 | |
function foo() { | |
return { | |
bar : function() { | |
return "bar"; | |
} | |
} | |
} | |
// operate immediately on the returned object | |
var bar = foo().bar(); // "bar" | |
function foo() { | |
return function() { | |
return "bar"; | |
} | |
}; | |
// operate immediately on the returned function | |
var bar = foo()() // "bar"; | |
// how about an object that has a method that returns the object? | |
var on = { | |
andOn : function() { | |
return on; // return the parent object | |
} | |
}; | |
// call `andOn` to get back an object with an `andOn` method | |
var bar = on.andOn(); // { andOn : function() { return on; }} | |
// so chaining indefinitely is possible! | |
on.andOn().andOn().andOn().andOn().andOn().andOn().andOn().andOn().andOn().andOn().andOn().andOn(); | |
// nice! | |
// so remember, returns are powerful things to have in your toolbelt! | |
// have fun with them | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment