Each of the scopes in JavaScript has an this
object that represents the object that called the function. In the global scope, this
the global object is represented (the one in the Web browser window
). If the contained this
function is a method of an object, that this
object is pointed to. So instead of writing the name of the object directly in the example above, use this
it instead, for example:
var human = { name: ' Hollinglin ', sayname:function () { console.log (this.name); }} Human.sayname ();
In this example, we use it directly person.name
, which increases the coupling between the method and the object (the dependency between them becomes stronger). This is problematic, and if we change the name of the variable, we have to modify the variable name in the method at the same time. Fortunately, JavaScript provides us with a way to solve this problem.
var person = { name: ' Hollinglin ', sayname:function () { console.log (person.name); } } Person.sayname ();
1. Change This
this
is usually automatically assigned, but we can change the direction of this. JavaScript gives us a 3 function method to change the point of this.
2.call () method
The first parameter of this method represents this
the object that is pointed to, and all subsequent arguments are arguments to the function. For example:
function Sayname (label) { console.log (label+ '---> ' +this.name);} var name = ' Zhang San '; var person1 = { name: ' John Doe '};var person2 = { name: ' King II '};sayname.call (window, ' Global '); ' Global---> Zhang San ' sayname.call (person1, ' Person1 '); ' Person1---> John Doe ' Sayname.call (person2, ' Person2 '); ' Person2---> Wang er '
3.apply () method
This method and call
method are all the same, except that when the parameter is passed, the call method can pass multiple parameters, and the Apply method can only pass one method, and the request is an array.
function Sayname (label) { console.log (label); Console.log (this.name);} var name = ' Zhang San '; var person1 = { name: ' John Doe '};var person2 = { name: ' King II '};sayname.apply (window,[' global '); ' Global---> Zhang San ' sayname.apply (person1,[' Person1 '); ' Person1---> John Doe ' sayname.apply (person2,[' Person2 '); ' Person2---> Wang er '
4.bind () method
The first parameter of the bind () method is the object that we want to point to in the function, followed by the value that we want to bind to the parameter of the function.
var obj = { name: ' xiaoming ' age:23 };function myName (age,gender) { console.log (this.name,age,gender); } var newName = myname.bind (obj);
NewName (); Xiao Ming undefined undefined var newName2 = Myname.bind (obj,18); NewName2 (); Xiaoming undefined var newName3 = myname.bind (obj,18, ' female '); NewName3 (); Xiaoming 18 female var newName4 = myname.bind (obj); NewName4 (18, ' female '); Xiao Ming 18 women
A thorough understanding of the call () method, the Apply () method, and the bind () method