Esercitazione JS

JS CASA JS Introduzione JS Dove si va Uscita JS Dichiarazioni JS Sintassi JS Commenti JS Variabili JS JS Let JS Cost Operatori JS JS aritmetica Assegnazione JS Tipi di dati JS Funzioni JS Oggetti JS Eventi JS Corde JS Metodi di stringa JS Ricerca di stringhe JS Modelli di stringhe JS Numeri JS Metodi numerici JS Matrici JS Metodi array JS Ordinamento matrice JS Iterazione dell'array JS Cost. array JS Date JS Formati data JS Metodi di acquisizione della data JS Metodi di impostazione della data JS JS matematica JS Casuale JS booleani Confronti JS Condizioni JS JS Switch Ciclo JS per JS Loop per In Ciclo JS per di JS Loop mentre JS Break Iterabili JS Insiemi JS Mappe JS Tipo JS Conversione del tipo JS JS bit a bit JS RegExp Errori JS Ambito JS JS sollevamento Modalità rigorosa JS JS questa parola chiave Funzione freccia JS Classi JS JS JSON Debug JS Guida allo stile JS Migliori Pratiche JS Errori di JS Prestazioni JS Parole riservate JS

Versioni JS

Versioni JS JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS IE / Edge Storia di JS

Oggetti JS

Definizioni di oggetti Proprietà dell'oggetto Metodi dell'oggetto Visualizzazione di oggetti Accessori per oggetti Costruttori di oggetti Prototipi di oggetti Iterabili di oggetti Insiemi di oggetti Mappe degli oggetti Riferimento all'oggetto

Funzioni JS

Definizioni delle funzioni Parametri di funzione Invocazione di funzione Chiamata di funzione Funzione Applica Chiusure di funzioni

Classi JS

Introduzione alla classe Eredità di classe Classe statica

JS Async

Richiamate JS JS asincrono JS Promesse JS Async/Attendere

JS HTML DOM

DOM Introduzione Metodi DOM Documento DOM Elementi DOM DOM HTML Moduli DOM DOM CSS Animazioni DOM Eventi DOM Ascoltatore di eventi DOM Navigazione DOM Nodi DOM Collezioni DOM Elenchi di nodi DOM

Distinta base del browser JS

Finestra JS Schermo JS Posizione JS Storia di JS Navigatore JS Avviso popup JS JS tempismo Biscotti JS

API Web JS

Introduzione all'API Web API dei moduli Web API Cronologia web API di archiviazione Web API Web Worker API di recupero Web API di geolocalizzazione web

JS AJAX

Introduzione all'Ajax AJAX XMLHttp Richiesta AJAX Risposta dell'AJAX File XML AJAX AJAX PHP AJAX ASP Database AJAX Applicazioni AJAX Esempi AJAX

JS JSON

Introduzione JSON Sintassi JSON JSON contro XML Tipi di dati JSON Analisi JSON JSON Stringify Oggetti JSON Matrici JSON Server JSON JSON PHP JSON HTML JSON JSONP

JS vs jQuery

Selettori jQuery jQuery HTML jQuery CSS jQuery DOM

Grafica JS

Grafica JS Tela JS JS Plotly JS Chart.js Grafico di Google JS JS D3.js

Esempi JS

Esempi JS JS HTML DOM Input HTML JS Oggetti HTML JS Eventi HTML JS Browser JS Editore JS Esercizi JS Quiz J.S Certificato JS

Riferimenti JS

Oggetti JavaScript Oggetti HTML DOM


Accesso agli oggetti JavaScript


Accessor JavaScript (getter e setter)

ECMAScript 5 (ES5 2009) ha introdotto Getter e Setter.

Getter e setter consentono di definire gli oggetti di accesso (proprietà calcolate).


Getter JavaScript (la parola chiave get)

Questo esempio usa una langproprietà per get il valore della languageproprietà.

Esempio

// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  language: "en",
  get lang() {
    return this.language;
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;

Setter JavaScript (la parola chiave impostata)

Questo esempio usa una langproprietà per set il valore della languageproprietà.

Esempio

const person = {
  firstName: "John",
  lastName: "Doe",
  language: "",
  set lang(lang) {
    this.language = lang;
  }
};

// Set an object property using a setter:
person.lang = "en";

// Display data from the object:
document.getElementById("demo").innerHTML = person.language;


Funzione JavaScript o Getter?

Quali sono le differenze tra questi due esempi?

Esempio 1

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object using a method:
document.getElementById("demo").innerHTML = person.fullName();

Esempio 2

const person = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.fullName;

Esempio 1 accesso fullName come funzione: person.fullName().

Esempio 2 accedere a fullName come proprietà: person.fullName.

Il secondo esempio fornisce una sintassi più semplice.


Qualità dei dati

JavaScript può garantire una migliore qualità dei dati quando si utilizzano getter e setter.

Utilizzando la langproprietà, in questo esempio, restituisce il valore della languageproprietà in maiuscolo:

Esempio

// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  language: "en",
  get lang() {
    return this.language.toUpperCase();
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;

Utilizzando la langproprietà, in questo esempio, viene memorizzato un valore maiuscolo nella languageproprietà:

Esempio

const person = {
  firstName: "John",
  lastName: "Doe",
  language: "",
  set lang(lang) {
    this.language = lang.toUpperCase();
  }
};

// Set an object property using a setter:
person.lang = "en";

// Display data from the object:
document.getElementById("demo").innerHTML = person.language;

Perché usare getter e setter?

  • Fornisce una sintassi più semplice
  • Consente la stessa sintassi per proprietà e metodi
  • Può garantire una migliore qualità dei dati
  • È utile per fare cose dietro le quinte

Object.defineProperty()

Il Object.defineProperty()metodo può essere utilizzato anche per aggiungere Getter e Setter:

Un controesempio

// Define object
const obj = {counter : 0};

// Define setters
Object.defineProperty(obj, "reset", {
  get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
  get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
  set : function (value) {this.counter -= value;}
});

// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;