Here is a rewritten version of your code:
var MyObject = function MyObject(selector) {
this.selector = selector;
this.init();
};
MyObject.prototype.alertId = function alertId() {
alert(this.selector);
};
MyObject.prototype.init = function init() {
var that = this;
// are we there already?
if (document.readyState == "interactive" ||
document.readyState == "complete") {
// yes, fire immediately
this.alertId();
} else {
// no, wait until the DOM is parsed
document.addEventListener("DOMContentLoaded", function(event) {
that.alertId();
});
}
};
var my_object = new MyObject('foo');
Let's go through this:
var MyObject = function MyObject(selector) {
this.selector = selector;
this.init();
};
This is the constructor for MyObject objects. As a convention, constructor functions are generally capitalized in Javascript, so I have renamed it.
In the constructor, we set up all the properties that are unique to each copy of MyObject
you create by calling new MyObject('selector string')
. In this case, it's just the selector
we get as the argument. After that, we call init()
on it on our new object.
Every MyObject
you create does not need its own init()
and alertId()
- it behaves the same for every copy. So in order not to waste memory, we create it on the prototype which all MyObjects
share:
MyObject.prototype.alertId = function alertId() {
alert(this.selector);
};
We could be certain that our selector is already available if you would include this script as the very last element at the bottom of your page, right before the closing tag. But a more robust way is to check:
MyObject.prototype.init = function init() {
var that = this;
// are we there already?
if (document.readyState == "interactive" ||
document.readyState == "complete") {
// yes, fire immediately
this.alertId();
} else {
// no, wait until the DOM is parsed
document.addEventListener("DOMContentLoaded", function(event) {
that.alertId();
});
}
};
If our DOM is already available to us, we execute alertId()
immediately. If not, we wait until it is by registering a callback for the DOMContentLoaded
event.
Note that I used that.alertId()
in the callback, not this.alertId()
. This is because when our callback function is executed, this
will be the window
context, not our current MyObject
object.
To get around this, I saved our current this
pointing to our object in the variable that
. that
remains available inside our callback function because Javascript has closures.
Please note that the above code only works for modern browsers. If you need compatibility with Internet Explorer 8 and older, you will need to workaround its missing support for DOMContentLoaded
with something like ContentLoaded.