English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Manuale di base JavaScript

Oggetto JavaScript

Funzione JavaScript

JS HTML DOM

BOM del browser JS

Manuale di base AJAX

Manuale di riferimento JavaScript

Chiamata di funzione JavaScript

call() permette di assegnare una funzione/metodo di un oggetto a un altro oggetto e invocarla.

function Product(name, price) {
  this.name = name;
  this.price = price;
}
function Food(name, price) {
  Product.call(this, name, price);
  this.category = "food";
}
document.write(new Food("cheese", 12).name);
Prova a vedere‹/›

Nell'esempio, call() fornisce un nuovo valore this alla funzione/metodo. Attraverso la chiamata, è possibile scrivere una volta una metodo e ereditare tale metodo in un altro oggetto senza doverlo riscrivere per l'oggetto nuovo.

Collega i costruttori degli oggetti tramite chiamata

Puoi usare call() per collegare i costruttori degli oggetti, come in Java.

function Product(name, price) {
  this.name = name;
  this.price = price;
}
function Food(name, price) {
  Product.call(this, name, price);
  this.category = "food";
}
function Toy(name, price) {
  Product.call(this, name, price);
  this.category = "toy";
}
let cheese = new Food("cheese", 12);
let robot = new Toy("robot", 85);
Prova a vedere‹/›

Chiamata di funzione senza specificare parametri

Nell'esempio seguente, abbiamo chiamato la funzione display senza passare parametri:

var name = "Seagull";
function display() {
  document.write(this.name);
}
display.call();
Prova a vedere‹/›