Water Cooler v2 Water Cooler v2 - 13 days ago 5
Javascript Question

Unable to add a property to an object using either the dot notation or the indexer notation?

I am trying to add a property named

params
to a property named
url
of a class named
Page
. The property
params
must be assigned the return value of an anonymous function.

The function runs just fine.

However, after assigning the return value of the function, when I check to see if the property
params
has been assigned to, I see no such property in the watches window or in the console. When I try to read back the property
params
from the
url
property, I get
undefined
.

Why is that? This happens whether I use the dot notation or the indexer notation to write / assign a value to the property. Below is my code:

var app =
{
...
};

$(document).ready(function() {
var page = new Page(app);
page.display();
});

var Page = function(app) {

this.url = window.location.href;
this.app = app;

this.url.params = (function() {

var p = { };

if (this.indexOf('?') < 0) return p;

var query = this.split('?')[1];

var pairs = query.split('&');

if (pairs === undefined || pairs.length == 0) return p;

for(var i = 0; i < pairs.length; i++) {
var pair = pairs[i].trim();

if (pair.length == 0) continue;

if (pair.indexOf('=') < 0) {
p[pair[0]] = '';
}
else {
var prop = pair.split('=');

p[prop[0]] = prop[1];
}
}

}.bind(this.url))();

this.display = function() {

debugger;

// over here, when I watch 'url', it does
// not have a 'params' property
};
};

Answer

Assigning properties to primitive string values does not cause an error. Instead it internally promotes the string type to a String object, performs the assignment and then discards the String object.

The reason for doing this is to enable the use of String.prototype getters and methods on primitive string values. (Similar considerations apply to using Number.prototype methods on primitive number type values)

In your case

this.url = window.location.href;

sets this.url to a primitive string value. Then when you set url.params to a function it is internally and effectively treated as

new String(this.url).params = function () ....

for the purposes of the assignment, but the String object created gets discarded after the statement has been executed. The primitive value in this.url does not gain properties - it is not an object data type and doesn't have properties.

Comments