简体   繁体   中英

What sort of setup is this and how to use it?

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?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM