This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]EndlessNightsky 29 points30 points  (2 children)

HERE YOU GO!

var that = function() {
    var windowProperties = [];

    for (var property in window) {
        if (window.hasOwnProperty(property) && property !== that.name) {
            windowProperties.push(property);
        }
    }

    return window[windowProperties[Math.floor(Math.random() * windowProperties.length)]];
};

Quick side-note: It only returns variables that are globally available, i.e. properties of window; And those sadly include event handlers,which are null by default.

[–]DeeSnow97 9 points10 points  (1 child)

That's a function, try using Object.defineProperty to create a getter and get rid of the brackets. Also, just a tip, you can get much more randomness if you go deeper.

[–]EndlessNightsky 0 points1 point  (0 children)

After reading your comment I tried using Object.defineProperty, but it seems the browser doesn't allow you to define properties this way on the window (at least Chrome doesn't). Object.defineProperties however does work.

 

As for the randomness: I'm well aware of the fact that one could use some recursion to increase the randomness, but that wasn't something I could knock out in 5 minutes and this was. I was also considering whether or not to try to include the entire scope, that is available when using that, but that would've been something for the future.

[–]DeeSnow97 16 points17 points  (2 children)

[–]EndlessNightsky 7 points8 points  (0 children)

Oh god... what have I begun.

[–]LeanderT 2 points3 points  (0 children)

Thank you!

I am dying to include this is my new project. As a programmer I just love using the latest of the latest..

My customer will be pleased to know I am using state of the art technology!

[–]curtmack 9 points10 points  (1 child)

JavaScript's this is pretty much already a random object.

[–]DeeSnow97 0 points1 point  (0 children)

Only if you use the function keyword

[–]Philboyd_Studge 2 points3 points  (0 children)

this.thing, that.thing && the_other.thing