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"));
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.
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");
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 )
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.
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.
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.
User’s name is Vipin Sharma and address is Jhansi UP
User’s name is Ashish Sharma and address is Mathura UP
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
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:
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
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:
Hoặc, cách khác
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”.
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.
Output
User’s name is Vipin Sharma and address is Jhansi UP.
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
Permissions in this forum:
You cannot reply to topics in this forum