1

For a project I am working on I am running into some Javascript coding from a previous programmer, this is basically structured as follows.

var c_test = {
    testVar : '',

    init : function()
    {
        c_test.testVar = 'Hello world!';
    },

    showMe : function()
    {
    alert(this.testVar);
    }
};

Example above created to show a basic version of the extensive coding I found like this. I suppose it is some form of object orientated JS, but I am unsure how to use it properly. For example, how would I go about calling this bit of code and running the 'showMe()' function?

Beittil
  • 117
  • 10
  • It's an Object literal as noted in the answers. There is only one instance and it's name is c_test so you can call showMe with `c_test.showMe()` For OOP JavaScript you have to know about prototype and constructor functions/initialisers. More on that here: http://stackoverflow.com/a/16063711/1641941 – HMR Feb 12 '14 at 14:08

3 Answers3

1

This is called an object literal. This is a straight forward way of building an object just by listing its properties and methods.

0

Consider c_test to be an object with two functions init and showMe and one field variable testVar

This is how would you call it.

c_test.showMe();

This can be also written as follows in OOP constructs. But of course, technically, there are difference between these two as well.

function c_test (){
    this.testVar = '';

    this.init= function(){
       this.testVar='Hello World';
    };

     this.showMe = function(){
       alert(this.testVar);
    };
};

Recommended Reading:

http://code.tutsplus.com/tutorials/the-basics-of-object-oriented-javascript--net-7670

Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124
  • I see, but this way the whole thing is basically written as a function. Apperently the way I have it needs a different method to call. – Beittil Feb 12 '14 at 11:11
  • Better put shared members on the prototype: http://stackoverflow.com/a/16063711/1641941 And for constructor functions there is a naming convention that states they should start with a Capital – HMR Feb 12 '14 at 14:09
0

To elaborate a little bit on Madhur Ahuja's answer, this way of coding is basically creating directly your object, as opposed to creating a "class" first and instantiating your object out of it.

This is possible because javascript is not class oriented so you can create objects directly. The drawback of this method is that it makes reuse of these kind of objects more complicated compared to creating a prototype first.

Silex
  • 1,707
  • 17
  • 24