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

JavaScript Basic Tutorial

JavaScript object

JavaScript function

JS HTML DOM

JS Browser BOM

AJAX Basic Tutorial

JavaScript Reference Manual

JavaScript Function Invocation

call() allows a function belonging to one object to be executed./method assigns to another object and calls it.

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);
Test and see‹/›

In the example, call() is directed to the function/The method provides a new value this. By calling it, you can write a method once and then inherit the method in another object without rewriting the method for the new object.

Use call to link the object's constructor function using a call

You can use call() to link the object's constructor function, similar to 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);
Test and see‹/›

Calling a function using a call without specifying parameters

In the following example, we call the display function without passing any parameters:

var name = "Seagull";
function display() {
  document.write(this.name);
}
display.call();
Test and see‹/›