3 ways to define a javascript class

Source: Internet
Author: User
ArticleDirectory
    • Introduction
    • 1. Using a function
    • 1.1. methods defined internally
    • 1.2. Methods added to the prototype
    • 2. Using Object literals
    • 3. Singleton using a function
    • Summary
3 ways to define a javascript classintroduction

Javascript is a very flexible object-oriented language when it comes to syntax. in this article you can find three ways of defining and instantiating an object. even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.

It's important to note that there are no classes in JavaScript. functions can be used to somewhat simulate classes, but in general Javascript is a Class-less language. everything is an object. and when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical classes ages.

1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by usingNewKeyword. To define properties and methods for an object created usingFunction (), You useThisKeyword, as seen in the following example.

 Function  Apple  (  Type  )  { This  .  Type  =  Type  ;  This  .  Color  =  "  Red  "  ;  This  .  Getinfo  =  Getappleinfo  ; }  //  Anti-pattern! Keep reading...  Function  Getappleinfo  (  )  {  Return  This  .  Color  +  '  '  +  This  .  Type +  '  Apple  '  ;  } 

To instantiate an object using the appleConstructor Function, Set some properties and call methods you can do the following:

VaRApple=NewApple('Macintosh');Apple.Color="Reddish";Alert(Apple.Getinfo());
1.1. methods defined internally

In the example above you see that the method getinfo () of the Apple "class" was defined in a separate function getappleinfo (). while this works fine, it has one drawback-you may end up defining a lot of these functions and they are all in the "Global namespece ". this means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. the way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:

 Function  Apple  (  Type  )  {  This  .  Type =  Type  ;  This  .  Color  =  "  Red  "  ;  This  .  Getinfo  =  Function  ()  {  Return  This .  Color  +  '  '  +  This  .  Type  +  '  Apple  '  ;  }  ;  } 

Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.

1.2. Methods added to the prototype

A drawback of 1.1. is that the method getinfo () is recreated every time you create a new object. sometimes that may be what you want, but it's rare. A more inexpensive way is to add getinfo () toPrototypeOf the constructor function.

 Function  Apple  (  Type  )  {  This  .  Type  =  Type  ;  This  . Color  =  "  Red  "  ;  }  Apple  .  Prototype  .  Getinfo  =  Function  (  )  {  Return  This  . Color  +  '  '  +  This  .  Type  +  '  Apple  '  ;  }  ; 

Again, you can use the new objects exactly the same way as in 1. and 1.1.

2. Using Object literals

Literals are shorter way to define objects and arrays in Javascript. To create an empty object using you can do:
VaR o = {};
Instead of the "normal" way:
VaR o = new object ();
For arrays you can do:
VaR A = [];
Instead:
VaR A = new array ();
So you can skip the class-like stuff and create an instance (object)
Immediately. Here's the same functionality as described in the previous
Examples, but using object literal syntax this time:

 VaR  Apple  =  {  Type  :  "  Macintosh  " ,  Color  :  "  Red  "  ,  Getinfo  :  Function  ()  {  Return  This  .  Color  +  '  '  + This  .  Type  +  '  Apple  '  ;  }  } 

In this case you don't need to (and cannot) Create an instance of the class, it already exists. So you simply start using this instance.

Apple.Color="Reddish";Alert(Apple.Getinfo());

Such an object is also sometimes calledSingleton. It "classical" extensions ages such as Java,SingletonMeans that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember ?) This concept makes no sense anymore since all objects are singletons to begin.

3. Singleton using a function

Again with the Singleton, eh?

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the Syntax:

 VaR  Apple  =  New  Function  ()  {  This  .  Type  =  "  Macintosh  "  ; This  .  Color  =  "  Red  "  ;  This  .  Getinfo  =  Function  ()  {  Return  This  .  Color  + '  '  +  This  .  Type  +  '  Apple  '  ;  }  ;  } 

So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.

Apple.Color="Reddish";Alert(Apple.Getinfo());

New Function (){...}Does two things at the same time: Define a function (an anonymous constructor function) and invoke itNew. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.

Summary

You saw three (plus one) ways of creating objects in JavaScript. remember that (despite the article's title) There's no such thing as a class in JavaScript. looking forward to start coding using the new knowledge? Happy JavaScript-ing!

This entry was posted on Friday, September 29th, 2006 and is filed under JavaScript. you can follow any responses to this entry through the RSS 2.0 feed. you can leave a response, or trackback from your own site.

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.