0

So I'm trying to name an object according to the website that I'm currently visiting using a class. I understand that location.hostname will tell me what website I'm currently visiting. I give you an example:

Site = function() {};
location.hostname = new Site();

Obviously that doesn't work. So, what would I have to do to make a new object of the Site class that had the name of the value of location.hostname? Thanks.

Aaron T
  • 1,092
  • 2
  • 10
  • 25
  • Do you want to assign the Site object to the hostname (thats what you doing above) or do you want the Site Object to be namend like the current site: You can use a "name" field in you Site Obj > Site.name = location.hostname – Tobi Dec 13 '13 at 08:22

2 Answers2

0

You need to use bracket notation to assign a variable name dynamically:

window[location.hostname] = new Site(); // Set
console.log(window[location.hostname]); // Get
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
0

Here are a couple different things:

  1. Does JavaScript have classes? - Short answer is no.

  2. So you must be asking about creating an object with some properties and functions that is specific to the site.

  3. There are several ways to do this. It is less about creating the right objects and more about accessing them. What is below is normal vanilla JavaScript and you should

    var sites = {};
    
    sites['stackoverflow.com'] = { config: {}, desc: 'stuff'};
    sites['stackoverflow.org'] = { config: {}, desc: 'stuff2'};
    sites['stackoverflow.net'] = { config: {}, desc: 'stuff3'};
    

I have shown a quick way above but use any object/prototype JavaScript method you want. There are many many good pages on this this topic.

Community
  • 1
  • 1
Ted Johnson
  • 4,315
  • 3
  • 29
  • 31