JS (3) Object-oriented programming

Source: Internet
Author: User

Object-oriented (OO) languages have a flag, that is, the concept of a class, and through a class can create multiple objects with the same properties and methods

One: To create an object

1, Factory mode:

The factory pattern is to use functions to encapsulate the creation of a particular interface with the details of the object, code as follows:

function  Createperson (name,age,job) {     var  o=new Object ();     O.name=name;     O.age=age;     O.job=job;     O.sayname=function () {     alert (this.name)        }      return o}var person1=createperson ("zhangningning", 21, " Doctor ")

Cons: No problem solving object recognition

2. Constructor Mode:

By creating a custom constructor,

The code is as follows:

function Person (name,age,job) {     this. name=name;       this. age= age;      this. sayname=function () {                 alert (this. Name)      }      }var person1=Newperson  ("zhangningning","  student")

Procedures for using the new operator:
(1), create a new object

(2) To assign a scope in the constructor to the new object

(3), execute the code in the constructor

(4), returns the new object

Disadvantage: Results in different instances of the same name function are not the same

An constructor attribute exists in the instance created by the constructor that points to the person

3, prototype mode

Each function has a prototype property, which is a pointer to an object that contains properties and methods that are shared by all instances of a particular type

Methods can be added to the prototype, and all instances will be shared

The values stored in the prototype can be accessed through an object instance, cannot be overridden by the object instance, and if an attribute is added to the instance with the same name as the property in the prototype object, the property in the prototype is overwritten

JS (3) Object-oriented programming

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.