Water Cooler v2 Water Cooler v2 - 1 year ago 62
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

to a property named
of a class named
. The property
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
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
from the
property, I get

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);

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];


this.display = function() {


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download