0

I have a few JavaScript files with some jQuery code. I am including this files to the my JavaServerPages files according to needs. I am wondering how can I create object, class or something common in JavaScript, which I can use in another JavaScript files?

I have created something similar to this:

function Util() {

    Util.getString = function() {
        var newString = "hello";
        return newString;
    }
}

It takes place in my basic JavaScript file. I have included it on my basic layout JSP file. I am using it in a jQuery function in another JavaScript file in this way:

var util = new Util(); 
Util.getString();

It works properly. But why can I not use util.getString()? util is my just created object, wright? What is the best solution to my issue?

woyaru
  • 5,544
  • 13
  • 54
  • 92
  • 1
    You're confusing JavaScript with a language that supports classes. You want to look at prototype inheritance: http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work – Joe Sep 12 '12 at 13:47
  • That one you created is a static method. When creating the objects with `new` they share this same prototype, think of it as a kind of inheritance. – dan-lee Sep 12 '12 at 13:53

3 Answers3

2

You should use prototype of the function, check here.

function Util() {
}

Util.prototype.getString = function() {
    var newString = "hello";
    return newString;
};

var util = new Util(); 
util.getString();
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

I assume you want a single static object in the global namespace on the page...

var util = new function(){
  this.getString = function(){
    ...
  }
}

or

var util = {
  getString : function(){
    ...
  }
}
tofarr
  • 7,682
  • 5
  • 22
  • 30
1

If you want to use your function without new()

var Util = {

    getString : function(){
    }

};

That way, getString() is already contained in an object. So you don't need to instantiate a class(function acts class in JavaScript) with new().

Robin Maben
  • 22,194
  • 16
  • 64
  • 99