Menu
Coddy logo textTech

Funzioni costruttrici

Fa parte della sezione Programmazione orientata agli oggetti del percorso JavaScript di Coddy. Lezione 4 di 56.

Le funzioni costruttore sono funzioni speciali in JavaScript che ti permettono di creare più oggetti con la stessa struttura e lo stesso comportamento.

Definisci una funzione costruttrice per una persona:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    return "Hello, my name is " + this.name;
  };
}

Crea un nuovo oggetto Person usando il costruttore:

const john = new Person("John", 30);
const tyler = new Person("Tyler", 35);

Dopo aver eseguito il codice precedente, john è un oggetto con proprietà:

// l'oggetto john contiene:
{
  name: "John",
  age: 30,
  greet: function() { return "Hello, my name is John"; }
}

Accedi alle proprietà e chiama i metodi:

console.log(john.name); // Restituisce: John
console.log(john.greet()); // Restituisce: Hello, my name is John
challenge icon

Sfida

  1. Crea una funzione costruttrice chiamata Book che accetta tre argomenti:
  • title (String)
  • author (String)
  • pages (Number)

La funzione dovrebbe impostarli come proprietà dell'oggetto creato. 

    2. Aggiungi un metodo chiamato getSummary che restituisce una stringa con alcune informazioni sul libro: this.title + " was written by " + this.author + " and has " + this.pages + " pages";

Provalo tu

// TODO: Crea una funzione costruttore chiamata Book che accetti tre argomenti (title, author, pages)


// TODO: Impostali come proprietà dell'oggetto creato


// TODO: Aggiungi un metodo chiamato getSummary che restituisca una stringa con alcune informazioni sul libro.
// Per esempio: Harry Potter was written by Rowling and has 500 pages


// Non modificare il codice qui sotto
const inputTitle = inp[0];          // Prima riga: titolo del libro
const inputAuthor = inp[1];         // Seconda riga: autore  
const inputPages = parseInt(inp[2]);// Terza riga: numero di pagine

const book = new Book(inputTitle, inputAuthor, inputPages);
console.log(book.getSummary());
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Programmazione orientata agli oggetti

Esercitati da solo: Compilatore JavaScript online