JS Object-oriented-create object

Source: Internet
Author: User

Factory mode

Factory mode returns the object (factory) by creating an object (raw material) in the function, and then by adding properties and methods to the object (machining).

1. Factory mode function Createperson (name,age,job) {//1. raw material var o = new Object ();//2. Processing O.name = Name;o.age = Age;o.job = Job;o. Sayname = function () {alert (this.name);};/ /3. Factory return o;} var yoomin = Createperson (' yoomin ', +, ' Programmer ');  Call, no new
Constructor mode

The constructor returns an object when new is added by adding properties and methods to this, and the constructor itself has no return value.

2. constructor mode function person (name,age,job) {this.name = Name;this.age = Age;this.job = Job;this.sayage = function () {alert (t his.age);}} var jay = new Person (' Jay ', ' singer ');  Call

Combination of constructor mode and prototype mode

Use constructors to define properties and prototype methods and shared variables:

Constructor Definition Properties:

function Person (name,age,job) {//constructor pattern defines instance properties THIS.name = Name;this.age = Age;this.job = Job;}

How to define a prototype method:

Person.prototype = {//prototype mode definition method and Shared properties Constructor:person,  //rewrite prototype changed constructor, fix back Sayname:function () {alert ( THIS.name);},sayjob:function () {alert (this.job);}}

Note: The literal definition of the prototype will change the prototype constructor point and need to be corrected.

To create an object:

var Kelly = new Person (' Kelly ', ' singer ');  Call Kelly.sayname ();  Kelly

  

JS Object-oriented-create object

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.