English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
call() permet d'appeler une fonction/La méthode est assignée à un autre objet et appelée.
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);Testez et voyez‹/›
Dans l'exemple, call() envoie une fonction/La méthode fournit une nouvelle valeur this. En appelant, vous pouvez écrire une méthode une fois, puis hériter cette méthode dans un autre objet sans avoir à réécrire cette méthode pour un nouvel objet.
Vous pouvez utiliser call() pour lier les constructeurs d'objets, comme en 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);Testez et voyez‹/›
Dans l'exemple suivant, nous avons appelé la fonction display sans passer de paramètres :
var name = "Seagull"; function display() { document.write(this.name); } display.call();Testez et voyez‹/›