0

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() ?

0

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

A static method in java can be accessed by an instance. Thats not the same in Javascript ? please confirm ?
can Can an instance of classfoo access doBar() ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.