Quale è la differenza fra queste due sintassi in JavaScript:
e quest'altra:....
....
writeError: function(errorMsg) {
alert(errorMsg);
}
};
function writeError(errorMsg) {
alert(errorMsg);
}
Quale è la differenza fra queste due sintassi in JavaScript:
e quest'altra:....
....
writeError: function(errorMsg) {
alert(errorMsg);
}
};
function writeError(errorMsg) {
alert(errorMsg);
}
darkOs, è giusta la sintassi? o hai messo i ":" al posto di "="
No la sintassi è giusta.
Ci sono molti modi in JavaSCript per definire le funzioni.
Oltre al costruttore new Function() ci sono:
definizione standard:
usata per le funzioni più semplici e normali (non strutturate).codice:function xyz(p1,p2){return p1+p2;}
assegnazione a variabile:
usate per poter poi usare la variabile per abbinare la funzione ad eventi o altri trigger del programma.codice:var xyz = function(p1,p2){return p1+p2;}
e poi c'è la versione in "stile" classe:
usualmente impiegata per definire funzioni (metodi) all'interno di classi ed oggetti vari.codice:xyz: function(p1,p2){return p1+p2;}
Non è affatto corretto quello che scrivi, softhare. Riporto un estratto della guida (https://developer.mozilla.org/En/Cor...function_scope) che ho postato nel precedente msg. Leggetevela, perché è davvero esaustiva...
Function constructor vs. function declaration vs. function expression
Compare the following:
[list=a][*]a function defined with the Function constructor assigned to the variable multiply
[*]a function declaration of a function named multiplycodice:var multiply = new Function("x", "y", "return x * y;");
[*]a function expression of an anonymous function assigned to the variable multiplycodice:function multiply(x, y) { return x * y; }
[*]a function expression of a function named func_name assigned to the variable multiplycodice:var multiply = function(x, y) { return x * y; };
[/list=a]codice:var multiply = function func_name(x, y) { return x * y; };
All do approximately the same thing, with a few subtle differences:
[list][*] There is a distinction between the function name and the variable the function is assigned to:
- The function name cannot be changed, while the variable the function is assigned to can be reassigned.
- The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:
The function name also appears when the function is serialized via Function's toString method.codice:var y = function x() {}; alert(x); // throws an error
On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.- As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.[/list=1]
- A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:
The following example shows how function names are not related to variables functions are assigned to. If a "function variable" is assigned to another value, it will still have the same function name:codice:function x() {} alert(x); // outputs x serialized into a string
codice:function foo() {} alert(foo); // alerted string contains function name "foo" var bar = foo; alert(bar); // alerted string still contains function name "foo"- A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:
Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:codice:function anonymous() { }
codice:var foo = new Function("alert(anonymous);"); foo();- Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:
codice:foo(); // alerts FOO! function foo() { alert('FOO!'); }- A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).
- Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should be avoided whenever possible.
It should be noted, however, that the parsing doesn't occur if to be repeatedly called is a nested-function of the defined with the Function constructor one. For example:
codice:var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is no longer parsed.
Forse dark0s non chiedeva una lezione sulle funzioni javascript, ma solo qualche parola sulla sintassi xyz: function() che non è ancora così comune.
Tra l'altro, nella trattazione indicata e copiata qua da carlomarx non si parla di questo modo di definire le funzioni, mentre mi pareva di aver capito che era proprio questa la domanda, come confermato anche da ganesh.
Quello che ha scritto softhare mi va bene come risposta, ma mi va bene anche quello che ha scritto carlomarx.
Leggerò ora quello che c'è scritto sul sito di mozilla.
appunto... la mia risposta era rivolta anche a questa domanda... se mi chiedi che differenza c'è traOriginariamente inviato da softhare
Forse dark0s non chiedeva una lezione sulle funzioni javascript, ma solo qualche parola sulla sintassi xyz: function() che non è ancora così comune.
ecodice:var myFnc = function() { }
ti dico: è la stessa che c' tracodice:myFnc: function() { }
ecodice:var divisione = 5 / 3
ovvero: nessuna dal punto di vista della funzione (o del valore primitivo, nel caso della divisione)! cambia solo il fatto che la sintassi coi due punti riguarda la dichiarazione letterale di un oggetto. Ma si tratta in entrambi i casi di espressioni di funzione. La vera differenza sta tra questi due esempi identici e le dichiarazioni di funzione, ovvero tra:codice:divisione: 5 / 3
che abbiamo visto prima, ecodice:// espressione di funzione var myFnc = function() { }
per cui rimando alla guida che ho postato.codice:// dichiarazione di funzione function myFnc() { }
Non si tratta di “un modo” di definire le funzioni. È come se mi dicessi che una funzione dichiarata così:Originariamente inviato da softhare
[...]
Tra l'altro, nella trattazione indicata e copiata qua da carlomarx non si parla di questo modo di definire le funzioni, mentre mi pareva di aver capito che era proprio questa la domanda, come confermato anche da ganesh.
è “un modo” di definire funzioni, diverso da:codice:var myArr = [ "luglio", 1998, function() { alert("ciao mondo"); }, true, false ];
...ma in realtà la differenza riguarda solo la sintassi necessaria per dichiarare gli oggetti, nel caso indicato da dark0s, e gli array in quest'ultimo esempio. Ma non ha nulla a che fare con le funzioni.codice:var myArr = new Array(); myArr[0] = "luglio"; myArr[1] = 1998; myArr[2] = function() { alert("ciao mondo"); }; myArr[3] = true; myArr[4] = false;
Ciao.![]()