javascript - developing a neutral constructor

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)

Answer №1

Almost there! The issue with your initial form is simply that you forgot to set the url property using the _url parameter.

function SiteProfile(_url) {
    //change the line below to:
    //this.url = _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;
}
var site = new SiteProfile("www.google.co.il");
document.write(site.name); // after making the correction, it will work as expected

Check out the fiddle for the initial form here: http://jsfiddle.net/BCnfx/

The problem with the second form is twofold. First, the main function should be named "SiteProfile" if you intend to create an instance of it. Secondly, you need to initialize the url property by passing in the url to the Site method.

//rename the function below to "SiteProfile", not "Site"
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;
    };
}

//instantiate like this instead.
var site = new SiteProfile();
site.Site("www.google.co.il");
document.write(site.name); // after the adjustments above, it will behave correctly

View the fiddle for the second form here: http://jsfiddle.net/BCnfx/1/

Answer №2

consider this initial instance:

function WebsiteProfile(_link) {
    this.link = _link;
    this.title = this.FetchTitleFromLink();
}

after that, you can perform :

var website = new WebsiteProfile("www.example.com");
 document.write(website.title);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

Appears as though time is slipping away during date conversions

I seem to be experiencing a strange issue where I lose a day when transitioning between MySQL and my JavaScript code, and I can't seem to figure out why. When I insert a date into the database (for example, 10/14/12), it appears as 10/13/12 in the dat ...

What sets Vuex apart from a traditional store object?

I'm currently utilizing Vuex for Vue 2 which is similar to Redux for React. Recently, I came across a helpful example that demonstrates updating a counter. Here is the code snippet: import Vuex from 'vuex' import Vue from 'vue' V ...

Vue event manager, accessible for all components

I have created a new Vue instance and assigned it to the window object, thinking that it would be accessible throughout all components. I expected this setup to allow me access to events emitted anywhere within my application. However, it seems like this ...

Struggling to manage texbox with Reactjs

Currently working in Reactjs with Nextjs and encountering a problem with the "text box". When I use the "value" attribute in the textbox, I am unable to input anything, but when I use the "defaultValue" attribute, I receive a validation message saying "Ple ...

What is the best way to retain checkbox states after closing a modal?

I have a modal that includes multiple checkboxes, similar to a filter... When I check a checkbox, close the modal, and reopen it, the checkbox I clicked on should remain checked. (I am unsure how to achieve this :/) If I check a checkbox and then click t ...

Methods for invoking a function from a separate .js file within React Native Expo

I'm new to using React and I've come across a challenge: In my Main.js file, there is a button: import * as React from 'react'; import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native'; import { M ...

Using discord.js does not allow line breaks in embed descriptions

const chatRoom = replyOptions.getRoom("room"); const header = replyOptions.getHeader("header"); const content = replyOptions.getContent("text"); const chatEmbed = new MessageEmbed() .setColor('DARK_VIVID_PURPLE') ...

Formik integration issue with MUI DatePicker causing error message: "date.isBefore is not a function"

I'm currently creating a form in React using Formik and MUI components. However, I encountered an error that says: date.isBefore is not a function TypeError: date.isBefore is not a function at DayjsUtils.isBeforeDay (http://localhost:3000/static/j ...

Unable to retrieve element using jQuery because it is specified by its href attribute. This pertains to

I'm having trouble accessing the "a" element with its href attribute. Specifically, I want to add a class to any element that has an href value of "#one". Check out this jsFiddle example. Using jQuery: // The tabs functionality is working correctly ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

Unable to retrieve the chosen option from the datalist

I am encountering an issue with a datalist where I can't seem to retrieve the value that is currently selected when a button is clicked. Despite following recommendations from various posts on Stack Overflow, my code still returns undefined. Interesti ...

Can one retrieve an express session using the sessionID given?

I have a NodeJS Express application with express-session that works well, however, it needs to be compatible with a cookie-less PhoneGap app. My question is: Can I access the data in an express session using the sessionID? I was thinking of adding the se ...

Verify whether a pop-up window has been opened

Situation: Greetings, I provide a sensitive service to my clients. However, some of them are generating advertisement popups (using JavaScript) on their websites where my service is integrated, causing issues for us. My service involves a .js file hosted ...

Converting input dates in nest.js using TypeScript formatting

Is it possible to set a custom date format for input in nest.js API request body? For example, like this: 12.12.2022 @ApiProperty({ example: 'ADMIN', description: 'Role name', }) readonly value: string; @ApiProperty({ ...

Tips for sending web form data straight to Google Sheets without the need for an authentication page

Exploring the Concept I have a unique idea to develop a landing page with a form that captures visitors' email addresses in a Google Sheet. After discovering a helpful post containing a Google App script for this purpose, I followed the guidelines o ...

Updating the CSS: Using jQuery to modify the display property to none

I am facing an issue with displaying an element that is defined as display:none in CSS. I tried to use the .show() function in jQuery, but it's not working as expected. Here's the code snippet: CSS .element { position: absolute; display: no ...

Variable assigned by Ajax no longer accessible post-assignment

Recently, I've written a script to fetch data from a SQL database and now I'm in the process of creating a JS wrapper for it. Utilizing certain functions, I call the script and extract information from the DB as soon as it becomes available. var ...

Is the Angular Library tslib peer dependency necessary for library publication?

I have developed a library that does not directly import anything from tslib. Check out the library here Do we really need to maintain this peer dependency? If not, how can we remove it when generating the library build? I have also posted this question ...