How objects in JavaScript access their properties

Source: Internet
Author: User

In JavaScript, when you access an object's own properties through its methods, you must use the This.fieldname method.

The reason is that the function in JavaScript is stateless, and when you access an object's properties, you must specify the current context state, which is to add the This keyword. If not specified, the context defaults to window.

Examples are as follows:

1     var obj =2    {3         Name: "James",4         showname:  function() {5            alert (name); 6         }7     }

Executes the obj.showname () output through the console as an empty string.

Cause: Obj.showname () executes alert (name); When the statement does not specify a context for name, it defaults to Window.name, and the value of Window.name is "", so output an empty string.

1     var obj =2    {3         Name: "James",4         showname:  function() {5             alert (this. Name); 6         }7     }

Change: Alert (this.name);

Execute the Obj.showname () output through the console as "James".

The behavior is consistent when the following definitions are used.

1     function Obj () {2         this. Name= "James"; 3     }4     obj.prototype.showname=function() {5         Alert (this. Name); 6     }7     varnew Obj ();

How objects in JavaScript access their properties

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.