JavaScript Object-Oriented definition member Method Example analysis _javascript skills

Source: Internet
Author: User

This article analyzes the JavaScript object-oriented definition member method. Share to everyone for your reference. Specifically as follows:

JavaScript is object-oriented, and the member method is defined as follows:

Copy Code code as follows:
<script language= "javascript" type= "Text/javascript" >
function Person (name,age) {
THIS.name = name;
This.age = age;
This.show = function () {
document.write (this.name+ "This year" +this.age+ "old");
}
}
var p1 = new Person ("Wang Meixin", 24);
P1.show ();
</script>

Description
(1) The constructor function is used here;
(2) this.show=function () This definition method, so that each instantiated object has this method. If you want an instantiated object to be owned separately, you can write the function externally, and then pass it along, as in the following example;
(3) the This.show function () can also have parameters.

functions are defined externally
Because the properties and methods of a JavaScript object are dynamically incremented, you can define this:

Copy Code code as follows:
<script language= "javascript" type= "Text/javascript" >
function Person (name,age) {
THIS.name = name;
This.age = age;
}
Function Show () {
Window.alert ("Hello," +this.name);
}
var p1 = new Person ("Wang Meixin", 24);
P1.show1 = show;//Note the difference between the function followed by () and not with (). Parenthesized notation gives the result to P1.show1 without parentheses to give the function to P1.show1.
P1.show1 ();
</script>

Or you can also define this:
Copy Code code as follows:
P1.show1 = function Show () {..........}

I hope this article will help you with your JavaScript programming.

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.