1

Is there an ObjectSpace in JavaScript?

Say I have these "classes" defined in isolated closures like this:

(function() {
  var Model;
  Model = (function() {
    function Model() {}
    return Model;
  })();
}).call(this);

(function() {
  var View;
  View = (function() {
    function View() {}
    return View;
  })();
}).call(this);

(function() {
  var Controller;
  Controller = (function() {
    function Controller() {}
    return Controller;
  })();
}).call(this);

Is there any way to look up all of those custom classes in JavaScript? Something like:

Object.classes;

Even if they were all in the same scope, is it possible?

var Model;
Model = (function() {
  function Model() {}
  return Model;
})();

var View;
View = (function() {
  function View() {}
  return View;
})();

Or would I just need to register them manually? Maybe like:

var ObjectSpace = {};
ObjectSpace.classes = [Model, View, Controller];

Just playing around with JavaScript/CoffeeScript and ideas from Ruby.

Community
  • 1
  • 1
Lance
  • 75,200
  • 93
  • 289
  • 503
  • What kind of pattern is that? Your code in example 1 does nothing at all, and example 2 does exactly the same as `function Model() {} function View() {}` – user123444555621 Oct 13 '11 at 05:55

3 Answers3

4

You would have to register them manually in order to have a list of them.

There is no such thing as a "class" in the javascript language so the language itself doesn't actually know about them. They are conventions used with prototypes or functions to provide a behavior similar to what is supported in other languages.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
3

Nope.

What you can do in coffeescript is

Classes = global.Classes = []

Classes.push class Model
    constructor: -> ...

or in javascript

global.Classes = {}

Model = Classes.Model = function(){
    ...
}
Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
1

You will need to do as you stated:

    ObjectSpace = {};
    ObjectSpace.classes = [Model, View, Controller];

In JavaScript, class constructs are not included. You are always interacting with and inheriting from Objects directly.

An example:

    function Model(name) {
        this.name = name;
    };
    Model.prototype.show = function() {
        alert('This model has name: '+this.name);
    };
    var model = new Model('test');
    model.show();   // 'This model has name: test'

When you use the new keyword, the js interpreter will first establish in the new instance a prototype link to the constructor function's prototype. This prototype object will be shared across all instances of, e.g., Model. If a property/method is changed on the prototype, all instances will immediately see that change, unless you do something like Model.prototype = { show: ... }. The reason is that you are literally making a new reference to for the prototype, but all current instances of Model point to the old reference.

Ryan
  • 1,557
  • 9
  • 11