This is the point in question--javascript 1

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.