Would you like to react to this message? Create an account in a few clicks or log in to continue.

Go down
Gã Càu Nhàu
Gã Càu Nhàu
Administrator
Posts : 49
Join date : 2017-08-05
Age : 28
https://thatkydieu.board-directory.net

Call, Apply và Bind trong JavaScript Empty Call, Apply và Bind trong JavaScript

Sat Aug 05, 2017 9:41 pm
Như chúng ta đều biết, trong javascript mỗi đối tượng có thuộc tính và phương thức riêng của nó. Hãy xem qua đoạn code sau:

Code:
function A(firstName,lastName){ 
    this.firstName = firstName; 
    this.lastName = lastName; 
    //I am using Template literals (Introduce in ES 6) ${this.firstName} to show the details 
    this.getUserDetails = function(city,state){ 
        var details = `User's name is ${this.firstName} ${this.lastName} and address is ${city} ${state}` 
        return details; 
    } 

 
function B(firstName,lastName){ 
    this.firstName = firstName; 
    this.lastName = lastName; 
    //I am using Template literals (Introduce in ES 6) ${this.firstName} to show the details 
    this.getUserDetails = function(city,state){ 
        var details = `User's name is ${this.firstName} ${this.lastName} and address is ${city} ${state}` 
        return details; 
    } 

 
//Create objects 
var a = new A("Vipin","Sharma"); 
var b = new B("Ashish","Sharma"); 
 
console.log(a.getUserDetails("Jhansi","UP")); 
console.log(b.getUserDetails("Mathura","UP"));
Gã Càu Nhàu
Gã Càu Nhàu
Administrator
Posts : 49
Join date : 2017-08-05
Age : 28
https://thatkydieu.board-directory.net

Call, Apply và Bind trong JavaScript Empty Re: Call, Apply và Bind trong JavaScript

Sat Aug 05, 2017 9:42 pm
Output

User’s name is Vipin Sharma and address is Jhansi UP

User’s name is Ashish Sharma and address is Mathura UP

Như chúng ta thấy, có 2 phương thức giống nhau cho 2 đối tượng và chúng ta đều sử dụng cả 2 để lấy thông tin của user. Chúng ta cần tránh việc lặp lại đoạn code này.

Giờ hãy xem qua cách dùng Call, Apply và Bind.

Trong đoạn code dưới đây, tôi tạo ra 2 hàm constructor và 1 phương thức. Tôi cũng tạo đối tượng cho cả 2 hàm constructor.

Code:
function A(firstName,lastName){ 
    this.firstName = firstName; 
    this.lastName = lastName; 

 
function B(firstName,lastName){ 
    this.firstName = firstName; 
    this.lastName = lastName; 

 
//create a single function to get user's details
var getUserDetails = function(city,state){ 
    var details = `User's name is ${this.firstName} ${this.lastName} and address is ${city} ${state}` 
    return details; 

 
//Create objects 
var a = new A("Vipin","Sharma"); 
var b = new B("Ashish","Sharma");
Gã Càu Nhàu
Gã Càu Nhàu
Administrator
Posts : 49
Join date : 2017-08-05
Age : 28
https://thatkydieu.board-directory.net

Call, Apply và Bind trong JavaScript Empty Re: Call, Apply và Bind trong JavaScript

Sat Aug 05, 2017 9:50 pm
Call()

Cú pháp

Tên hàm.call( tên đối tượng, tham số truyền vào )

Code:
//a and b are objects for A and B function constructor. 
//Jhansi and UP are parameters passed into the function. 
console.log(getUserDetails.call(a,"Jhansi","UP")) 
console.log(getUserDetails.call(b,"Mathura","UP"))

Output

User’s name is Vipin Sharma and address is Jhansi UP

User’s name is Ashish Sharma and address is Mathura UP

Không có dấu ngoặc đơn nào phía sau tên hàm bỏi vì nó được truy cập như một đối tượng. Chúng ta đang sử dụng phương thức single (getUserDetails) cho cả 2 đối tượng.
Gã Càu Nhàu
Gã Càu Nhàu
Administrator
Posts : 49
Join date : 2017-08-05
Age : 28
https://thatkydieu.board-directory.net

Call, Apply và Bind trong JavaScript Empty Re: Call, Apply và Bind trong JavaScript

Sat Aug 05, 2017 9:53 pm
Apply()

Cú pháp

Tên hàm.apply( tên đối tượng, tham số truyền vào )

Phương thức apply() hoạt động khá giống với call(), nó cũng nhận chỉ 2 tham số.

Đối tượng.

Một mảng các tham số được truyền vào trong hàm.

Code:
//array of parameters that will pass to the function. 
var arr = ["Jhansi","UP"]; 
var arr1 = ["Mathura","UP"]; 
 
//arr array for object a call 
console.log(getUserDetails.apply(a,arr)) 
 
//arr1 array for object b call 
console.log(getUserDetails.apply(b,arr1))
Output

User’s name is Vipin Sharma and address is Jhansi UP

User’s name is Ashish Sharma and address is Mathura UP
Gã Càu Nhàu
Gã Càu Nhàu
Administrator
Posts : 49
Join date : 2017-08-05
Age : 28
https://thatkydieu.board-directory.net

Call, Apply và Bind trong JavaScript Empty Re: Call, Apply và Bind trong JavaScript

Sat Aug 05, 2017 9:55 pm
Bind()

Bind() có một chút khác so với call() và aplly().

Xem qua ví dụ sau:

Code:
//passing parameters to bind()   
console.log(getUserDetails.bind(a,"Jhansi","UP"))

Nếu ta chạy đoạn code trên, nó sẽ trả về một đối tượng hàm, nhưng nó không phải là kết quả chính xác.

Output

Code:
function (city,state){
var details = User's name is ${this.firstName} ${this.lastName} and address is ${city} ${state}
return details;
}

Thay vì trả về một kết quả thì nó trả về một đối tượng hàm. Vậy muốn đạt được mục đích, chúng ta làm theo cách sau:

Code:
//Storing function object to a variable. 
var obj = getUserDetails.bind(a); 
//calling function object with parameters. 
console.log(obj("Jhansi","UP"));

Hoặc, cách khác

Code:
//we can directly pass the parameters to function objets 
console.log(getUserDetails.bind(a)("Jhansi","UP"));

Output

User’s name is Vipin Sharma and address is Jhansi UP

Từ khóa this

Hãy thay đổi đoạn code trên, thay vì truyền tên đối tượng tôi sẽ dùng “this”.

Code:
var getUserDetails = function(city,state){   
    var details = `User's name is ${this.firstName} ${this.lastName} and address is ${city} ${state}`   
    return details;   
}   
//this is referring to global object
console.log(getUserDetails.bind(this)("Jhansi","UP"));

Output

User’s name is undefined and address is Jhansi UP

Trong ouput, firstname và lastname có giá trị undefined. Khi chúng ta xác định nó trong global namespace thì nó thuộc về đối tượng global nhưng chúng ta chưa định nghĩa FirstName và LastName trong global namespace.

Code:
//Parameters - City and State 
var getUserDetails = function(city,state){   
    var details = `User's name is ${this.firstName} ${this.lastName} and address is ${city} ${state}`   
    return details;   
}   
 
//now firstname and lastname are belong to global object 
var firstName = "Vipin"; 
var lastName = "Sharma"; 
 
//this is referring to global object 
console.log(getUserDetails.bind(this)("Jhansi","UP"));

Output

User’s name is Vipin Sharma and address is Jhansi UP.

Techtalk via c-sharpcorner.com
Sponsored content

Call, Apply và Bind trong JavaScript Empty Re: Call, Apply và Bind trong JavaScript

Back to top
Permissions in this forum:
You cannot reply to topics in this forum