开发者

Javascript object creation on the fly

I'm sure I've seen some examples of thi开发者_如何学Cs 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.


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.


This is the syntax for inline object creation (In this case returned from a function.).

function ResolveGeoCode() {
    return {
        Ad1: "Hello ",
        Ad2: "World"
    };
}


In your code try to change:

var Location;

in

var Location = {};


var ResolveGeoCode = {
    Ad1 : "Hello",
    Ad2 : "World"
}

var String1 = ResolveGeoCode.Ad1; //This contains "Hello "?
var String2 = ResolveGeoCode.Ad2; //This contains "World"?


What you're missing here is that {} are the markers for a dynamic object in ECMAScript. So when you see code like ChaosPandion's that's what's actually happening.

In your example you could pretty much change the word function to class and you're almost there to a full class.


In the "ResolveGeoCode" function:

  1. Do what Mic described above: Initialize the variable "Location" by using the empty object constructor, "{}".

  2. Try adding members dynamically like this:

Location['Ad1'] = 'Hello';
Location['Ad2'] = 'World';


You can also do like a constructor

constructor{ 
Object.assign(this)
}
or You can eventually pass values 
 constructor(val){ 
 Object.assign(this, val)
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜