Improved way to initialize JavaScript objects

I created a custom object called Stream with the following structure:

function Stream(id, info, container){
    var self = this;

    this.id = id;
    this.paddedId = ("00000" + this.id).substr(-5,5);
    this.live = info['live'];
    this.autoplay = info['autoplay'];
...

To instantiate an object, I use the code snippet below:

var stream = new Stream(1, streamInfo, "stream");

Sometimes, I need to create multiple objects of this type at once. I would like to find a cleaner way to initialize it while keeping my functions intact. Is there a way to achieve something similar to the code snippet below?

var stream = new Stream({
        'id': 1,
        'live': true,
        'autoplay': false
     });

If not exact, then perhaps a similar approach.

Answer №1

To pass parameters to the constructor, you can group them into an 'options' parameter.

If you want to maintain functions within 'Stream', utilize its prototype to define functions that will be accessible to all instances of Stream.

function Stream(options){
   this.id = options.id;
   this.autoplay = options.autoplay;
   // ... additional variable setup
}

Stream.prototype.foo = function() {
  // code for function foo
}
 
Stream.prototype.bar = function() {
 // code for function bar
}

Example :

var stream = new Stream({ id : 'myId', autoplay : true });
stream.foo();
stream.bar();

Answer №2

One way to utilize anonymous functions is shown below:

var MyClass = (function () {

    var self = function (options) {

        // These are our default options
        this.options = {
            name: 'John',
            lastName: 'Doe'
        }

        // Extend the object with provided options
        $.extend(this.options, options);
    };

    self.prototype.get = function (attr) {
        return this.options[attr];
    };

    self.prototype.set = function (attrName, attrValue) {
        this.options[attrName] = attrValue;
    };

    self.prototype.whatsMyName = function () {
        $('.' + this.get('name')).html(this.get('name') + ' ' + this.get('lastName'));
    };

    return self;
})();

var Tom = new MyClass({
    name: 'Tom',
    lastName: 'Mathew'
});

var Allen = new MyClass({
    name: 'Allen',
    lastName: 'C'
});

Tom.whatsMyName();
Allen.whatsMyName();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div class="Tom"></div>
<div class="Allen"></div>

Answer №3

One way to access values in a Stream Constructor is by passing a config object.

function Stream(fonfig){
   var self = this;
   var info = config.info || {};
   this.id = config.id;

   this.paddedId = ("00000" + this.id).substr(-5,5);
   this.live = info['live'];
   this.autoplay = info['autoplay'];
}

Then, you can use it like this:

var stream = new Stream({
    'id': 1,
    'live': true,
    'autoplay': false
 });

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

Unusual shift in the modal's behavior occurs when the parent component's style.transform is applied

I have encountered an unusual issue with a modal's appearance and functionality. The modal is designed to enlarge images sent in a chat, with the chat upload preview div serving as the parent element and the modal as the child element. This strange be ...

Incorporating the angular UI router effectively by reusing the same templateUrl and controller multiple times

Exploring the AngularUI Router framework for the first time, I am curious about how to enhance the code snippet below. Everything is functioning well at the moment, but as the project progresses, it will feature 20 questions or more. I want to avoid repea ...

Tips for downloading an XLSX file

I have a file in the assets directory that I would like to be able to download for my project. <button className='p-2 bg-green-600 my-3 text-white '> <href='../../../Assets/file/form_upload_lead.xlsx'>Download Format Upl ...

Reading and extracting data from a massive XML document using Node.js

Currently, I am facing a challenge with an XML file that is quite large - exceeding 70mb. My goal is to parse this data in Node.js for potential data visualizations down the line. After giving it some thought, I decided that converting the XML file to JSON ...

What exactly is HTML cloud storage all about?

As I work on developing an app through phonegap, one question that comes to mind is the possibility of storing information online. For instance, if there's a number variable that increases when a button is pressed, can this value be saved somewhere an ...

Converting HTML content to L20N format after dynamically modifying the DOM

While working on my knockout based website, I decided to implement L20n to enhance the user experience. However, I encountered a few challenges along the way. One of the issues I faced was related to dynamically creating views. I was wondering how I could ...

Running the command Yarn build with Vite.js and React.js is encountering issues and is not functioning properly

Lately, I've been experimenting with Vite in my React projects. However, when I execute the command yarn build, it creates a Build folder but the application fails to work. When I open the index.html file, all I see is a blank page. Interestingly, e ...

Reordering database information using javascript and php

Is the title completely accurate? Here's my issue: I operate a website where users can upload images. I am looking to allow users to organize their uploaded images in a specific order and then preview them exactly as they arranged them. The organizi ...

JavaScript comparing elements within an array

I need help extracting all the names from an array with URLs containing '/blekinge' and presenting them in a list. Here's what I have so far: const allLocations = locations.map((location) => <li>{location.url}</li> ) I&a ...

Advantages of placing script src tags at the top of the body versus placing them at the bottom of the body

I've heard that it's best to place the script tags right before the closing body tag. However, when I follow this advice, my angularJS expressions don't seem to compute correctly for some reason. When I place the script tags in that location ...

Chart featuring top corners smoothly rounded off for a unique doughnut design

I've been attempting to create a D3.js chart similar to the one shown in the first screenshot: https://i.sstatic.net/GgP1d.png While I can easily replicate a chart like the second screenshot using the default examples, the challenge arises when I tr ...

Tips for adding text to your d3 force layout

Looking to incorporate text into a force layout using SVG. I've created an svg group and added a circle successfully, but having trouble with the text. Here's the code snippet: var node = svg.selectAll("g") .data(measures.nod ...

Executing a JavaScript function from V8 in C++: A Step-by-Step Guide

When I want to run a basic Javascript program using v8, I follow these steps: // Define a string containing the JavaScript source code. v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "'Hello' + ', from Javascript!&a ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...

I am having trouble with Fullcalendar not loading my JSON data to display events

I've been experimenting with the fullcalendar JavaScript library, but I'm struggling to load data from my MySQL database onto the calendar. When I test my db-connect.php file, it does return the first entry in the table, yet the calendar remains ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Exploring the interaction between child objects and cube objects in Three.js

I have a main cube object with wireframe: var cubeGeometry = new THREE.CubeGeometry( 50, 50, 50 ); Also, I have some cubes that are not wireframed: var cubeTemp = new THREE.CubeGeometry( 10, 10, 10 ); I want to rotate cubeGeometry and have cubeTemp rot ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

Using Angular to swap out the component's selector with HTML code

Consider the following component: @Component({ selector: 'passport-cell', templateUrl: './passport-cell.component.html', styleUrls: ['./passport-cell.component.scss'] }) export class PassportCell { @Input() public la ...

Is it possible to retrieve elements by their ID when the ID values are constantly changing?

I'm facing an issue with accessing dynamic IDs using `getElementById`. I require this value to perform random calculations involving different elements. MY CODE <div class="col-lg-4" v-for="data in datas"> <button class="btn btn-outline-d ...