A method that binds a function in an object called this object.
In JavaScript, the definition of an object is this:
var xiaoming = {
Name: ' Xiaoming ',
birth:1990
};
However, if we bind a function to xiaoming, we can do more things. For example, write an age () method, and return to Xiaoming:
var xiaoming = {
Name: ' Xiaoming ',
birth:1990,
Age:function () {
var y = new Date (). getFullYear ();
return Y-this.birth;
}
};
Xiaoming.age; function Xiaoming.age ()
Xiaoming.age (); This year the call is 25, and next year the call becomes 26.
A function that is bound to an object is called a method, and it is no different from a normal function, but it uses the This keyword internally, what is this?
Inside a method, this is a special variable that always points to the current object, that is, the xiaoming variable. So, This.birth can get Xiaoming's birth attribute.
Let's take it apart and write:
function Getage () {
var y = new Date (). getFullYear ();
return Y-this.birth;
}
var xiaoming = {
Name: ' Xiaoming ',
birth:1990,
Age:getage
};
Xiaoming.age (); 25, normal results
Getage (); NaN
Call function Getage () How did you return nan? Please note that we have entered a big hole in JavaScript.
If this is called inside the function of JavaScript, who is this?
The answer is, depending on the situation!
This is the point in question--javascript 1