cram2208
cram2208

Reputation: 416

How to access property inside function constructor javascript

I need to manipulate HTML tags through a class as such:

/*
 * Begin: HTML Class
 */
HTML = function(el, property) { // Construct
    this.el = el;
    this.property = new Array;
    var HTML = document.createElement(el);

    this.element = function() {
        return HTML;
    };

    HTML.objects.push(this);

    if (typeof property == "object")
        for (i in property)
            this.addProperty(i, property[i]);
};

HTML.objects = new Array; // Registers all new HTML objects.

// Adds a new property to HTML current element.
HTML.prototype.addProperty = function(name, value) {
    this.property[name] = value;
    this.getHTML()[name] = value;
};

// Retrieves current HTML element.
HTML.prototype.getHTML = function() {
    return this.element();
};

// Clones current HTML objects with same construct arguments.
HTML.prototype.clone = function() {
    return new HTML(this.el, this.property);
};
/*
 * End: HTML Class
 */

Each time new HTML(...) is called, newly created instance must be stored within HTML.objects which is a static property of HTML whose role is to keep track of all HTML objects. But now when it reaches to HTML.objects.push(this); it will return undefined property error. After, I tried to call for HTML.objects in firebug and it was definitely defined. As function(...) { ... } is called at instantiation, shouldn't it be able to access HTML.objects property?
Thanks.

Upvotes: 3

Views: 1805

Answers (1)

Moppo
Moppo

Reputation: 19275

The proprety HTML.objects doesn't exists because in your constructor's scope HTML is the variable you have defined here:

var HTML = document.createElement(el);

so, when you make this call:

HTML.objects.push(this);

you are trying to access the proprey of the just declared HTML variable.

In fact, if you try to replace the first line with:

var HTML_INNER = document.createElement(el);

It'll work

Upvotes: 2

Related Questions