How to emulate "class" in JavaScript

Source: Internet
Author: User

JavaScript as a weak type of speech, there is no similar to the concept of "class" in java,c#, but there are many times in the actual development of such requirements, there are now know that there are two ways to simulate.
1. By declaring an object, you can have the following code:

var people = {        age:12,        name: "Jack",        Sex: "Male",        setage:function (value) {            this.age = value;        },        getage:function () {            return this.age;        },        setname:function (value) {            this.name = value;        },        getname:function () {            return this.name;        },        setsex:function (value) {            this.sex = value;        } ,        getsex:function () {            return this.sex;        },        //There are other methods in addition to the read methods of these properties        sayhi:function () {            document.write ("hi,everybody!")        ,},        //can also write        function Sayhi () {            document.write ("Hi, Everybody! ");        }    }

Such a "Class" is written, can be called by the following way:
People.age (or people.getage) to get age information
People.setage to modify the age
It is important to note that since "people" is not a real class, but rather an object of JavaScript, all elements in the people, whether attributes or methods, are treated as attributes by JavaScript, so they are all separated by ",".

2. By declaring a function

function people () {        var age,name,sex;        This.getage = function () {            return this.age;        }        This.setage = function (value) {            this.age = value;        }    }

The related operation is basically the same as the first method.
The application scenarios of the two methods are not clear at present and need further study.

How to emulate "class" in JavaScript

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.