login
Dutch master remixes and JS object pitfalls posted: Fri 2013-08-30 17:51:35 tags: daylogs, tech
I guess I wrote my own collaborative content management software to host daylogs. With blackjack. And hookers. In fact, forget the collaboration.

I'm an unabashed fan of remix culture, so when I happened across a retouch of Vermeer's painting, "Girl with a Pearl Earring" stylized as a "selfie", I posted it to my gesischtsbuch, and Frank Smith responded with a link to worth1000.com where graphic artists and 'shop hobbyists do a lot of that sort of thing, and much more.

Figured out something new about objects in JavaScript. I had a temp variable x which I was using to pull in and operate on data instead of verbose references to form input element values. Then as my code progressed, I decided I wanted to pull that form data into properties of an object, instead of having to refer back to the form repeatedly.

But for brevity's sake, if I knew I wouldn't have to refer to a datum for more than one step, I was assigning data directly to x, e.g.
x = $("#FirstName").val();
x = x.toUpperCase();

....all under the mistaken mindset that var x would retain its "objectness". But no, x was always just a name by which to access a reserved memory-space styled as an Object. Assigning a value to x would logically discard all the properties attached to its previous object value. But not only that, when you assign a scalar value to a variable, I guess scalars don't magically become able to receive dynamic properties! So the app silently ignored my attempts to implicitly add properties by assigment, and returned undefined on reference to the expected property instead.

var x = new Object();
x.AnPropertie = 7;
console.log(x.AnPropertie);     //console says 7
x = 7;     //replaces original object
x.MoarProperty = "bleem";     //won't work as expected
console.log(x.MoarProperty);    //undefined

Solution: Instead of trying to use bare x to stash values that would be awkward to refer to repeatedly in longhand, use x.temp, or x.t, heck even x.x will work. Or else dedicate another shorthand temp variable, such as t.

While I was researching that, I discovered something else interesting about JS objects notation though: You can refer to properties by objName.propName, and also by object["propName"]. So, code like this totally works the way you would expect:
oEmply = new Object();
oEmply.FirstName = "John";
x = "FirstName";
console.log(oEmply[x]);     //console says "John"