0

Solution at the end!

Okey, I know it sounds confusing, hopefully after the example you will understand. Lets say I have a persons object (I want to use object's instead of function object's because it resembles static classes).

Persons = {

}

Now, inside this persons object I have a simple person object.

Persons = {
    person:function(name){
       var $ = this;
       $.name = name;
    }
}

Now, let's say I want to have a john property that it's an instance of the Persons.person object, how do I do that? None of this work:

Persons = {
    person:function(name){
       var $ = this;
       $.name = name;
    },
    john:new this.person("John"),
    john:function(){return new this.person("John")},
    john:return new this.person("John")
}

Thank you, hopefully you get what I'm trying to do, if not, just ask! :)


Edit: Here's another example (as it's been marked as a duplicate but the duplicate talks about properties and I'm talking about methods).

See, this works:

Keys = {
    key:function(keyCode){
        var $ = this;
        $.keyCode = keyCode;
    },
    ctrl:new Keys.key(8)
}

But it only works because Keys is a global variable, if Keys was out of scope (maybe an internal object in the code) it woudn't work (I think). This doesn't work.

var Keys = {
    key:function(keyCode){
        var $ = this;
        $.keyCode = keyCode;
    },
    ctrl:new Keys.key(8)
}

Edit2:

Found a solution, instead of using an object directly to simulate static classes, I use the function(){} version with the new keyword in front, so that it makes an object, and it simulates a static class, but you can use the function(){} notation.

To get it clear, the above examples would be:

var Keys = new function(){
        var $ = this;
        $.key = function(keyCode){
            var $ = this;
            $.keyCode = keyCode;
        },
        $.control = new $.key(8);
    }

and:

var Persons = new function(){
    var $ = this;
    $.person = function(name){
       var $ = this;
       $.name = name;
    },
    $.john = new $.person("John");
}

Hope it helps if somebody has the same crazy problem :) Thanks to everyone who answered and read!

undefined
  • 3,949
  • 4
  • 26
  • 38
  • Check http://stackoverflow.com/questions/6084872/an-object-that-returns-an-instance-of-itself –  Sep 15 '14 at 23:27
  • Thanks but that isn't quite what I need, you see I believe there must be a way of creating a new object and assigning it to an object property, just like you would on the function(){} version of this code instead of the object {} version :) – undefined Sep 15 '14 at 23:32

0 Answers0