Thủ Thuật Hướng dẫn What does call () do in javascript? 2022
Bùi Công Duy đang tìm kiếm từ khóa What does call () do in javascript? được Cập Nhật vào lúc : 2022-09-30 22:24:09 . Với phương châm chia sẻ Thủ Thuật Hướng dẫn trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi đọc tài liệu vẫn ko hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Tác giả lý giải và hướng dẫn lại nha.Method Reuse
With the call() method, you can write a method that can be used on different objects.
Nội dung chính- Method ReuseAll Functions are MethodsWhat is this?The JavaScript call() MethodThe call() Method with ArgumentsIntroduction to the JavaScript call() methodUsing the JavaScript call() method to chain constructors for an objectUsing the JavaScript call() method for function borrowingWhat's the difference between call () and apply ()?What is the use of call?What happens when you call a function in JavaScript?Why we need call and apply in JavaScript?
All Functions are Methods
In JavaScript all functions are object methods.
If a function is not a method of a JavaScript object, it is a function of the global object (see previous chapter).
The example below creates an object with 3 properties, firstName, lastName, fullName.
Example
const person =
firstName:"John",
lastName: "Doe",
fullName: function ()
return this.firstName + " " + this.lastName;
// This will return "John Doe":
person.fullName();
Try it Yourself »
In the example above, this refers to the person object.
this.firstName means the firstName property of this.
Same as:
this.firstName means the firstName property of person.
What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. Alone, this refers to the global object. In a function, this refers to the global object. In a function, in strict mode, this is undefined. In an sự kiện, this refers to the element that received the sự kiện. Methods like call(), apply(), and bind() can refer this to any object.The JavaScript call() Method
The call() method is a predefined JavaScript method.
It can be used to invoke (call) a method with an owner object as an argument (parameter).
With call(), an object can use a method belonging to another object.
This example calls the fullName method of person, using it on person1:
Example
const person =
fullName:
function()
return this.firstName + " " + this.lastName;
const person1 =
firstName:"John",
lastName: "Doe"
const person2 =
firstName:"Mary",
lastName: "Doe"
// This will return "John Doe":
person.fullName.call(person1);
Try it Yourself »
This example calls the fullName method of person, using it on person2:
Example
const person =
fullName: function()
return this.firstName + " " + this.lastName;
const person1 =
firstName:"John",
lastName: "Doe"
const person2 =
firstName:"Mary",
lastName: "Doe"
//
This will return "Mary Doe"
person.fullName.call(person2);
Try it Yourself »
The call() Method with Arguments
The call() method can accept arguments:
Example
const person =
fullName: function(city, country)
return this.firstName + " " + this.lastName + "," + city + "," +
country;
const person1 =
firstName:"John",
lastName: "Doe"
person.fullName.call(person1, "Oslo", "Norway");
Try it Yourself »
Summary: in this tutorial, you will learn about the JavaScript call() method and how to use it more effectively.
Introduction to the JavaScript call() method
In JavaScript, a function is an instance of the Function type. For example:
function add(x, y) return x + y; console.log(add instanceof Function); // true
Code language: JavaScript (javascript)The Function.prototype type has the call() method with the following syntax:
functionName.call(thisArg, arg1, arg2, ...);
Code language: JavaScript (javascript)In this syntax, the call() method calls a function functionName with the arguments (arg1, arg2, …) and the this set to thisArg object inside the function.
- The thisArg is the object that the this object references inside the function functionName.The arg1, arg2, .. are the function arguments passed into the functionName.
The call() method returns the result of calling the functionName().
The following example defines the add() function and calls it normally:
function add(x, y) return x + y; let result = add(10, 20); console.log(result); // 30
Code language: JavaScript (javascript)The following calls the add() function but use the call() method instead:
function add(x, y) return x + y; let result = add.call(this, 10, 20); console.log(result); // 30
Code language: JavaScript (javascript)By default, the this inside the function is set to the global object i.e., window in the web browsers and global in Node.js.
Note that in the strict mode, the this inside the function is set to undefined instead of the global object.
Consider the following example:
var greeting = 'Hi'; var messenger = greeting: 'Hello' function say(name) console.log(this.greeting + ' ' + name);
Code language: JavaScript (javascript)Inside the say() function, we reference the greeting via the this value. If you just invoke the say() function via the call() method as follows:
say.call(this,'John');
Code language: JavaScript (javascript)It’ll show the following output to the console:
"Hi John"
Code language: JavaScript (javascript)However, when you invoke the call() method of say function object and pass the messenger object as the this value:
say.call(messenger,'John');
Code language: JavaScript (javascript)The output will be:
"Hello John"
Code language: JavaScript (javascript)In this case, the this value inside the say() function references the messenger object, not the global object.
Using the JavaScript call() method to chain constructors for an object
You can use the call() method for chaining constructors of an object. Consider the following example:
function Box(height, width) this.height = height; this.width = width; function Widget(height, width, color) Box.call(this, height, width); this.color = color; let widget = new Widget('red', 100, 200); console.log(widget);
Code language: JavaScript (javascript)Output:
Widget height: 'red', width: 100, color: 200
Code language: JavaScript (javascript)In this example:
- First, initialize the Box object with two properties: height and width.Second, invoke the call() method of the Box object inside the Widget object, set the this value to the
Widget object.
Using the JavaScript call() method for function borrowing
The following example illustrates how to use the call() method for borrowing functions:
const car = name: 'car', start() console.log('Start the ' + this.name); , speedUp() console.log('Speed up the ' + this.name); , stop() console.log('Stop the ' + this.name); , ; const aircraft = name: 'aircraft', fly() console.log('Fly'); , ; car.start.call(aircraft); car.speedUp.call(aircraft); aircraft.fly();
Code language: JavaScript (javascript)Output:
Start the aircraft Speed up the aircraft Fly
Code language: JavaScript (javascript)How it works.
First, define a car object with one property name and three methods start, speedUp, and stop:
const car = name: 'car', start() console.log('Start the ' + this.name); , speedUp() console.log('Speed up the ' + this.name); , stop() console.log('Stop the ' + this.name); , ;
Code language: JavaScript (javascript)Second, define the aircraft object with one property name and a method:
const aircraft = name: 'aircraft', fly() console.log('Fly'); , ;
Code language: JavaScript (javascript)Third, call the start() and speedUp() method of the car object and the fly() method of the aircraft object. However, passing the aircraft as the first argument into the start() and speedUp() methods:
car.start.call(aircraft); car.speedUp.call(aircraft); aircraft.fly();
Code language: JavaScript (javascript)Inside the start() and speedUp() methods, the this references the aircraft object, not the car object. Therefore, the this.name returns the 'aircraf' string. Hence, the methods output the following message:
Start the aircraft Speed up the aircraft
Code language: plaintext (plaintext)Technically, the aircraft object borrows the start() and speedUp() method of the car object. And function borrowing refers to an object that uses a method of another object.
The following example illustrates how the arguments object borrows the filter() method of the Array.prototype via the call() function:
function isOdd(number) return number % 2; function getOddNumbers() return Array.prototype.filter.call(arguments, isOdd); let results = getOddNumbers(10, 1, 3, 4, 8, 9); console.log(results);
Code language: JavaScript (javascript)Output:
[ 1, 3, 9 ]
Code language: JavaScript (javascript)How it works.
First, define the isOdd() function that returns true if the number is an odd number:
function isOdd(number) return number % 2;
Code language: JavaScript (javascript)Second, define the getOddNumbers() function that accepts any number of arguments and returns an array that contains only odd numbers:
function getOddNumbers() return Array.prototype.filter.call(arguments, isOdd);
Code language: JavaScript (javascript)In this example, the arguments object borrows the filter() method of the Array.prototype object.
Third, call the getOddNumbers() function:
let results = getOddNumbers(10, 1, 3, 4, 8, 9); console.log(results);
Code language: JavaScript (javascript)In this tutorial, you have learned about the JavaScript call() method and how to use it more effectively.
Was this tutorial helpful ?