Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 15862  / 15 Years ago, wed, january 6, 2010, 12:00:00

I'm sure I've seen some examples of this in jquery. But for me, the following code does not work. The firebug debugger tells me that: 'Location is undefined'. Could you tell me if this is possible?



function ResolveGeoCode() {
var Location;
Location.Ad1 = Hello ;
Location.Ad2 = World;

return Location;
}

var loc = ResolveGeoCode();
var String1 = loc.Ad1; //This contains Hello ?
var String2 = loc.Ad2; //This contains World?


Could a name be given to this type of feature I'm looking for?



Thanks.


More From » javascript

 Answers
84

This is what's happening:



function ResolveGeoCode() {
// Location is declared, but its value is `undefined`, not `object`
var Location;
alert(typeof Location); // <- proof pudding

// Failing here because you're trying to add a
// property to an `undefined` value

Location.Ad1 = Hello ;
Location.Ad2 = World;

return Location;
}


Fix it by declaring Location as an empty object literal before trying to add properties to it:



function ResolveGeoCode() {
var Location = {};
alert(typeof Location); // now it's an object

// Programmatically add properties
Location.Ad1 = Hello ;
Location.Ad2 = World;

return Location;
}


If you know the properties and their corresponding values ahead of time, you can use a more inline approach:



function ResolveGeoCode() {
var Location = {
Ad1: Hello ,
Ad2: World
};

// ...further manipulations of Location here...

return Location;
}


Read here for more on object literals.


[#97905] Monday, January 4, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrodfletchers

Total Points: 75
Total Questions: 94
Total Answers: 95

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
jarrodfletchers questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Mon, Jan 21, 19, 00:00, 5 Years ago
Sun, Dec 16, 18, 00:00, 6 Years ago
Sun, Nov 4, 18, 00:00, 6 Years ago
;