English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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‹/›
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‹/›