Three simple methods of Javascript Object encapsulation

Source: Internet
Author: User

Use the keyword new to create an object

Js code

Function Person (name, age) {this. name = name; this. age = age;} var p = new Person (); // You can also fill in initialization attributes, such as new Person ("lingceng", 22)

Directly create an Object using an Object

It can be seen that this method is very convenient to expand.

Js code

Var obj = new Object (); // var ={}; obj. name = "lingceng"; obj. age = 22;

Create with JSON (object literal description is more accurate, but JSON is better understood)

Starting with Javascript1.2, you can create an object more quickly.

Js code

Var p = {name: "lingceng", // "name": "lingceng is resolved in the same way as quotation marks. gender:" male "};

Practice

It is suitable for practice to create objects in combination with constructors and prototype modes.

Js code

Function Person (name, age) {// instance attributes // Copy this multiple times during the instance. name = name; this. age = age;} Person. prototype = {// http://developer.51cto.com/art/200907/134913.htm // The constructor property always points to the constructor that created the current object // because the prototype is replaced, you need to restore the construtor's default point to constructor: Person, showName: function () {alert ("ShowName in prototype:" + this. name) ;}, showAge: function () {alert (this. age) ;}} var p = new Person ("lingceng", 22); p. showAge (); // 22



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.