JavaDeveloper
JavaDeveloper

Reputation: 5660

Static methods in JavaScript

If I have a class declared in prototype.js

var ClassFoo = Class.create();
ClassFoo.prototype = {
        initialize: function() {

        },
        type: 'ClassFoo'
};

If I declare a method ClassFoo.doBar = function() { log("foobar") }

  1. Is it the same as/equivalent to creating a static method in java ?

  2. Can an object of classfoo access doBar() ?

Upvotes: 0

Views: 130

Answers (1)

jfriend00
jfriend00

Reputation: 707258

Yes, methods on the constructor are analogous to static methods in other OOP languages. They are available globally (or in whatever scope the constructor is defined in) and are not associated with any particular instance of that object (which is pretty much what a static method is).

Any code anywhere in your project can access them as ClassFoo.doBar(). Your methods of ClassFoo can access it that way too. There are no other shortcuts for accessing them (even from methods).

One thing to remember is that functions in Javascript are objects and can have properties just like any other object in Javascript. So, assigning:

ClassFoo.doBar = function() {...};

is just assigning a property to the ClassFoo object and it can be used like any property on any object.

ClassFoo.doBar();

Upvotes: 1

Related Questions