How can I pass an object into a function's prototype in Javascript?

In my quest to delve deeper into JavaScript, I've embarked on creating my very own MVC library. My current investigation involves examining the source code of backbone.js which can be found here.

When defining a Collection in backbone.js, it involves assigning it to a JavaScript variable as shown below:

var AppCollection = Backbone.Collection.extend({ model: BACKBONE_MODEL })

The creator employs underscore internally and utilizes the `prototype` for the `Collection`, extending it with underscore's `_.extend()` method like so:

_.extend(Collection.prototype, Events, {})
. The empty object passed in serves as a container for all the methods related to the Collection object, such as the `model` key containing the Model object previously defined.

I'm intrigued by the idea of sidestepping the underscore dependency and incorporating my custom prototypical methods for the Collection. How can I introduce an object with the `model` key into my Collection object?

Below is a snippet of what I've been working on:

(function(Pigeon, root, factory) {
    root[Pigeon] = factory();
} ('Pigeon', this, function() {

    var Pigeon = {};

    // Model
    var Model = Pigeon.Model = function() {
        this.attributes = {};
    };

    // Collection
    var Collection = Pigeon.Collection = function(models) {

    };

    // View
    Pigeon.View = {};

    // Controller
    Pigeon.Controller = {};

    return Pigeon;

}));

Answer №1

Instead of relying on "_", there are alternative methods available for extending an object or class without using "_.extend()".

One option is to utilize Object.assign for extending prototypes, although this approach may not be fully supported by all browsers (especially Internet Explorer). Another alternative is to create a custom extend function using Object.keys(mixinClass).

Example using Object.assign:

function a() {
  this.propOne = "one";
}

a.prototype.methodOne = function() {
  document.write("<br/>I am methodOne from a");
}

function b() {
  this.propTwo = "two";
}

b.prototype.methodTwo = function() {
  document.write("<br/>I am methodTwo from b");
}

function assigned() {
  a.call(this);
  b.call(this);
}

// Combine properties from different objects and set constructor
Object.assign(assigned.prototype, a.prototype, b.prototype);
assigned.constructor = assigned;

var x = new assigned();
document.write("<pre>I am assigned and I look like: \n" + JSON.stringify(x, 2, null) + "</pre>");
x.methodOne();
x.methodTwo();

Custom extend function example:

function myExtend() {
  var args = Array.prototype.slice.apply(arguments);
  var target = args.shift();
  var extended = {};
  args.forEach(function(o) {
    Object.keys(o).forEach(function(k) {
      extended[k] = o[k];
    });
  });
  Object.keys(extended).forEach(function(k) {
    if (!target[k])
      target[k] = extended[k];
  });
}

function a() {
  this.propOne = "one";
}

a.prototype.methodOne = function() {
  document.write("<br/>I am methodOne from a");
}

function b() {
  this.propTwo = "two";
}

b.prototype.methodTwo = function() {
  document.write("<br/>I am methodTwo from b");
}

function assigned() {
  a.call(this);
  b.call(this);
}

myExtend(assigned.prototype, a.prototype, b.prototype);
assigned.constructor = assigned;

var x = new assigned();
document.write("<pre>I used myExtend and I look like: \n" + JSON.stringify(x, 2, null) + "</pre>");
x.methodOne();
x.methodTwo();

This technique involves mixin where you can extend simple objects or combine multiple classes to create a subclass with methods of various types. However, keep in mind that this approach creates copies of the properties and methods instead of using references. Nevertheless, it should serve your purpose effectively.

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

Resolving a Tricky Challenge with jQuery's

I am facing an issue with a function that animates images through crossfading. This function is responsible for rotating banners on a website. By calling the function as animateSlideshow("play"), it starts animating and sets up a timeout. On the other hand ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: https://i.sstatic.net/2YBEF.png https://i.sstatic.net/YCEHG.png The main query is whether it is acceptable in HTML to w ...

After loading the ajax content, remember to include the JavaScript files

Here's the situation: I am importing some php files, one of which includes a slider that requires .js files. However, when I make an ajax call, the file is imported but the js files are not. Is this normal behavior? I attempted the following: var s ...

AngularUi Mobile Modal List Display

I attempted to implement the code from 32400236/dynamically-generate-modals-with-mobileangularui but encountered issues. I also tried using the following: <div class="access-item" ng-repeat="item in items track by $index"> <a ui-turn-on="$index" ...

The shadow effect in three.js differs from that in Unity 3D

When I import a 3D model in .fbx format to my scene using three.js, I noticed that the shadow effect is not as sharp as when using Unity. The shadows appear too blurry. Is there a way to adjust the shadowMap setting in three.js to match the shadow quality ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

Bootstrap3 Remote Modal experiencing conflict due to Javascript

Utilizing a bootstrap modal to showcase various tasks with different content but the same format is my current goal. However, I am encountering an issue when attempting to make the textareas editable using JavaScript. The conflict arises when I open and cl ...

Stop automatic resizing on mobile device after postback

Encountered an issue with a website I'm currently developing. It's not causing any problems, but I want to enhance the user experience. My aim is to maintain the zoom levels of mobile devices after a postback. To provide more context, there is a ...

Using jQuery to animate a div within a PHP echo statement

<li> <a id="collection" href="collections.php"> <span class="glyphicon glyphicon-th white"> Collections</span> </a> </li> <?php include "pagination.php" ?> <script> $("#collection").clic ...

Looking to simplify the complex JSON structure by converting it into an array using JavaScript

Being a newcomer to javascript, I am struggling with breaking down a complex structure into an array. The current structure is as follows: [ { "Key": "ProducePRINKA0370001", "Record": { "docType": "Produce", "PR ...

Combining two arrays filled with objects to form a collection of Objects on a Map

In my JavaScript code, I'm receiving data from a WebService that looks like this: { "fire": { "totalOccurence": 2, "statsByCustomer": [ { "idCustomer": 1, "occurence": 1 }, { "idCustomer": 2, ...

Breaking down a JSON Object in Angular 4: Step-by-step Guide

I am working on integrating a JSON API with an Angular 4 frontend, and my goal is to display the data from this JSON Object. Here is the code I have used: <div *ngFor="let Questionnaire of struc.data"> <span>{{Questionnaire.attributes.con ...

The JavaScript function document.getElementById.onclick is not functioning as expected

One issue I am facing involves counting all downloads on my website. My current approach is to increment a value in my database each time a download button is clicked, and then display this value. Despite trying multiple methods, the download count always ...

What is the method for storing API status JSON in the state?

Can anyone help me figure out why the json in the register state is returning an empty object after console.log(register); from that state? import React, { useEffect, useState } from "react"; import { Formik } from "formik"; // * icons ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Is there a way to streamline this JavaScript Defer code?

I am currently managing a JavaScript bootstrapper module that I want to keep as clean and straightforward as possible. Here is the current code snippet: function bootStrapper() { xmlRepository.getAll().done(function (result) { autoPolicyForm ...

"Interactive jQuery feature allows users to edit table content live with the ability to update and delete data via

I am working on implementing live editing, updating, and deleting functionality in a table using jQuery. However, I have encountered two problems: When clicking the pen icon from order #3 to #1, it requires 3 clicks, but when clicking from order #1 to ...

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Utilizing a factory as the data source in angular-datatables leads to unexpected errors

Is it possible to use a factory as a source data in angular-datatables? Basically, I want to retrieve data in a variable and use it as the data source. UPDATED (06/22/2016) This is my updated factory: statisticsModule.factory('globalFactory&apos ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...