Similar Question:
Constructors in Javascript objects
I am exploring the concept of creating classes in JavaScript. I am struggling to grasp it fully.
Now, I am curious if it's possible to create a constructor in JavaScript, similar to what can be done in languages like C#.
I have experimented with a few approaches:
Approach 1:
function SiteProfile(_url) {
this.url = "";
this.name = this.ExtractNameFromURL();
}
SiteProfile.prototype.ExtractNameFromURL = function () {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
Approach 2:
function Site() {
this.url = "";
this.name = "";
this.Site = function (_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
}
this.ExtractNameFromURL = function () {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
}
Both classes should take a URL and extract the name from it without including "www." or ".com".
I want to know if I can design a class that allows me to create an instance like this:
var site = new SiteProfile("www.google.co.il");
document.write(site.name); // because this currently does nothing
(Apologies for any language errors)