Skip to content

Instantly share code, notes, and snippets.

@loristissino
Created March 29, 2019 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loristissino/46c0f787f538c6f330cb960b868b72c4 to your computer and use it in GitHub Desktop.
Save loristissino/46c0f787f538c6f330cb960b868b72c4 to your computer and use it in GitHub Desktop.
Modi diversi di definire oggetti e classi in js
'use strict';
// oggetto semplice
var book1 = {
title: "The Handmaid's Tale",
author: "Margaret Atwood",
year: 1985,
}
console.log(book1.title);
console.log(book1);
// oggetto definito tramite una funzione (vecchio stile)
function Book(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}
var book2 = new Book("The Ice People", "Maggie Gee", 1999);
console.log(book2.title);
console.log(book2);
// definizione di metodi tramite il prototipo
Book.prototype.setYear = function(year) {
this.year = year;
}
book2.setYear(2000);
console.log(book2.year);
// classe (ECMA6)
class Person {
constructor (firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
setAge(age) {
this.age = age;
}
}
var ma = new Person("Margaret Atwood", "Margaret Atwood", 79);
console.log(ma);
ma.setAge(80);
console.log(ma);
// classe derivata
class Author extends Person {
constructor(firstName, lastName, age) {
super(firstName, lastName, age);
this.books = [];
}
addBook(book) {
if (!book.author) {
book.author = this.getFullName();
}
this.books.push(book);
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
// return [this.firstName, this.lastName].join(" ");
}
}
var mg = new Author("Maggie", "Gee", 2019-1948);
mg.addBook(book2);
console.log(mg);
mg.addBook(new Book("Light Years", null, 1985));
console.log(mg);
// classe con getter e setter
class Bus {
constructor(id, plate) {
this._id = id;
this._plate = plate;
}
get id() {
return this._id;
}
set id(value) {
this._id = value;
}
get plate() {
return this._plate;
}
set plate(value) {
this._plate = value;
}
get seats() {
return this._seats;
}
set seats(value) {
this._seats = value;
}
}
let b1 = new Bus(3, "FG003DK");
b1.seats = 30;
console.log(b1.seats);
// classe con accesso agli attributi in stile jQuery
class Sensor {
constructor(id) {
this._id = id;
this._value = 0;
}
value(v) {
if (v!==undefined) {
this._value = v;
return this;
}
else {
return this._value;
}
}
color(v) {
if (v!==undefined) {
this._color = v;
return this;
}
else {
return this._color;
}
}
}
let s = new Sensor(67);
s.value(80).color("red");
console.log(s.value());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment