Visualizzazione dei risultati da 1 a 9 su 9

Discussione: domanda sulle funzioni

  1. #1
    Utente di HTML.it
    Registrato dal
    Oct 2005
    Messaggi
    79

    domanda sulle funzioni

    Quale è la differenza fra queste due sintassi in JavaScript:

    ....
    ....
    writeError: function(errorMsg) {
    alert(errorMsg);
    }

    };
    e quest'altra:

    function writeError(errorMsg) {
    alert(errorMsg);
    }

  2. #2

  3. #3
    Utente di HTML.it L'avatar di ganesha
    Registrato dal
    Jan 2003
    Messaggi
    357
    darkOs, è giusta la sintassi? o hai messo i ":" al posto di "="

  4. #4
    Utente di HTML.it
    Registrato dal
    Oct 2005
    Messaggi
    79
    No la sintassi è giusta.

  5. #5
    Ci sono molti modi in JavaSCript per definire le funzioni.

    Oltre al costruttore new Function() ci sono:

    definizione standard:
    codice:
    function xyz(p1,p2){return p1+p2;}
    usata per le funzioni più semplici e normali (non strutturate).

    assegnazione a variabile:
    codice:
    var xyz = function(p1,p2){return p1+p2;}
    usate per poter poi usare la variabile per abbinare la funzione ad eventi o altri trigger del programma.

    e poi c'è la versione in "stile" classe:
    codice:
    xyz: function(p1,p2){return p1+p2;}
    usualmente impiegata per definire funzioni (metodi) all'interno di classi ed oggetti vari.
    Tecnolgie per l'arte.
    Arti per la tecnologia.
    softhare

  6. #6
    Utente di HTML.it L'avatar di carlomarx
    Registrato dal
    Oct 2009
    Messaggi
    1,669
    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
    codice:
    var multiply = new Function("x", "y", "return x * y;");
    [*]a function declaration of a function named multiply
    codice:
    function multiply(x, y) {
    	return x * y;
    }
    [*]a function expression of an anonymous function assigned to the variable multiply
    codice:
    var multiply = function(x, y) {
    	return x * y;
    };
    [*]a function expression of a function named func_name assigned to the variable multiply
    codice:
    var multiply = function func_name(x, y) {
    	return x * y;
    };
    [/list=a]
    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:
    1. The function name cannot be changed, while the variable the function is assigned to can be reassigned.
    2. 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:
      codice:
      var y = function x() {};
      alert(x); // throws an error
      The function name also appears when the function is serialized via Function's toString method.

      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.
    3. 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]
    4. 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:
      codice:
      function x() {}
      alert(x); // outputs x serialized into a string
      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 foo() {}
      alert(foo); // alerted string contains function name "foo"
      var bar = foo;
      alert(bar); // alerted string still contains function name "foo"
    5. 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:
      codice:
      function anonymous() {
      }
      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:
      var foo = new Function("alert(anonymous);");
      foo();
    6. 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!');
      }
    7. 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).
    8. 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.

  7. #7
    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.
    Tecnolgie per l'arte.
    Arti per la tecnologia.
    softhare

  8. #8
    Utente di HTML.it
    Registrato dal
    Oct 2005
    Messaggi
    79
    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.

  9. #9
    Utente di HTML.it L'avatar di carlomarx
    Registrato dal
    Oct 2009
    Messaggi
    1,669
    Originariamente 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.
    appunto... la mia risposta era rivolta anche a questa domanda... se mi chiedi che differenza c'è tra
    codice:
    var myFnc = function() { }
    e
    codice:
    myFnc: function() { }
    ti dico: è la stessa che c' tra
    codice:
    var divisione = 5 / 3
    e
    codice:
    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:
    // espressione di funzione
    var myFnc = function() { }
    che abbiamo visto prima, e
    codice:
    // dichiarazione di funzione
    function myFnc() { }
    per cui rimando alla guida che ho postato.

    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.
    Non si tratta di “un modo” di definire le funzioni. È come se mi dicessi che una funzione dichiarata così:
    codice:
    var myArr = [
    	"luglio",
    	1998,
    	function() { alert("ciao mondo"); },
    	true,
    	false
    ];
    è “un modo” di definire funzioni, diverso da:
    codice:
    var myArr = new Array();
    myArr[0] = "luglio";
    myArr[1] = 1998;
    myArr[2] = function() { alert("ciao mondo"); };
    myArr[3] = true;
    myArr[4] = 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.

    Ciao.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.