Last active
October 23, 2017 03:22
-
-
Save hlecuanda/9a453c0b1169f133c0973d9e8a50a020 to your computer and use it in GitHub Desktop.
Making sense of function expressions, declarations, invocations and incantations :S
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
//Excerpts from https://dmitripavlutin.com/6-ways-to-declare-javascript-functions/ | |
// also in https://jsbin.com/bozilam | |
//for reference | |
// Function Declaration ----------------------------------------------- | |
var count = function(array) { // Function expression | |
return array.length; | |
}; | |
var methods = { | |
numbers: [1, 5, 8], | |
sum: function() { // Function expression | |
return this.numbers.reduce(function(acc, num) { // func. expression | |
return acc + num; | |
}); | |
} | |
}; | |
console.log (count([5, 7, 8])); // => 3 | |
console.log(methods.sum()); //` => 14 | |
// Anonymous Function Expressiom --------------------------------------- | |
var getType = function(variable) { | |
return typeof variable; | |
}; | |
console.log(getType.name); // => '' | |
// When the expression has the name specified, this is a named function expression. | |
//It has some additional properties in comparison with simple function expression: | |
// A named function is created, i.e. name property holds the function name | |
// Inside the function body a variable with the same name holds the function object | |
// Let's use the above example, but specify a name in the function expression: | |
var getType = function funName(variable) { | |
console.log(typeof funName === 'function'); // => true | |
return typeof variable; | |
}; | |
console.log(getType(3)); // => 'number' | |
console.log(getType.name); // => 'funName' | |
console.log(typeof funName === 'function'); // => false | |
function log(obj){ | |
console.log('log inspector start ==========='); | |
obj.getOwnPropertyNames().forEach( | |
function (val, idx, array) { | |
console.log(val + ' -> ' + obj[val]); | |
} | |
); | |
console.log('log inspector done ============'); | |
} | |
log("caca"); | |
log(getType(3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment