Un oggetto JavaScript è un mapping tra chiavi e valori. Le chiavi sono stringhe e valori possono essere qualsiasi cosa. Ciò rende gli oggetti naturali in forma per le hashmap.
Le funzioni sono oggetti regolari con la capacità aggiuntiva di essere richiamabile.
DAhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#.22Normal.22_objects.2C_and_functions
Ciò significa che si può fare cose come:
function test(){
console.log(1);
}
var a = test;
a();
o
var test2 = function(){
console.log(2);
}
o autochiamata
//sorry for the indentation.
(
function(){
console.log(3);
}
)()
o crearne strutture
var testHash = {
a : 1,
b : function(){
console.log(4);
}
}
testHash.b();
testHash['b']();
e creare la funzione difficile da chiamare:
//in a browser environment
window['test3'] = function(){
console.log(5);
}
window['test space'] = function(){
console.log(6);
}
test3() //no error
test space() //error :D
EDIT: L'utente vuole sapere di più su funzioni di Monitoraggio:
Perché questo lavoro?
(
function(){
console.log(3);
}
)()
E 'facile da seguire in 2 fasi:
La parentesi, se sappiamo che una funzione è come le altre variabili, e sappiamo che la parentesi è solo per gruppi composti o funzioni di chiamata.
var test_1 = 'string example';
var length = (test_1).length; // the same that test_1.length
senso in:
var test_1 = 'string';
var test_2 = ' example';
var length = (test_1 + test_2).length; // the same that test_1.length
invece di:
var test_1 = 'string';
var test_2 = ' example';
var aux = test_1 + test_2;
var length = aux.length; // the same that test_1.length
Ora, questo ha senso per te ?:
var length = ('string example').length; // instead the first example
Secondo passo, possiamo cambia la stringa per la funzione .. e chiamala
(function(){ ... })()
perché è interessante? Bene, ora appare il concetto di chiusura.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Le chiusure sono uno strumento molto importante in javascript.
Grazie, questa è davvero una grande risposta. Puoi spiegarmi come funziona la funzione autocall? –
Ho fatto un aggiornamento. –