Exploring the functionality of the .apply method in relation to classes and prototypes

I'm currently utilizing TypeScript to create classes using the Dependency Injection design pattern. In the code of the Injector class, there is a particular line that stands out: car.apply(car, [new doors]). The expectation is that by executing the main class, we should be able to use the injected dependencies and methods as arguments. However, it appears that the .apply method does not actually execute the function as intended! So, what is truly happening here?

var car = function (){
    function car(doorsClass){
        this.doorsClass = doorsClass;
this.color('red');
this.doorsNum(4);
    }
    car.prototype.color = function(color){
    console.log('Car color is '+color);
    }
    car.prototype.doorsNum = function(doorsNum){
    console.log('Car has '+this.doorsClass.doors(doorsNum)+' doors');
    }
return car;
}

var doors = function (){
    function doors(){ }
    doors.prototype.doors = function(num){
    return num;
    }
return doors;
}

car.apply(car, [new doors]);

Answer №1

There were a few issues with your code, primarily related to the modules not being executed properly. As a result, your variable that was supposed to point to the constructor ended up pointing to the module instead.

Another major issue was trying to use apply on the constructor to create a new instance. While there are various workarounds available, depending on your targeted version of Javascript, the following code seems to achieve what you intended:

var applyCtor = function(){
    var tempCtor = function() {};
    return function(ctor, args){
        tempCtor.prototype = ctor.prototype;
        var instance = new tempCtor();
        ctor.prototype.constructor.apply(instance,args);
        return instance;
    }
}();

var CarClass = (function (){
    function car(doorsClass){
        this.doorsClass = doorsClass;
    }
    car.prototype.color = function(color){
    console.log('Car color is '+color);
    }
    car.prototype.doorsNum = function(doorsNum){
    console.log('Car has '+this.doorsClass.doors(doorsNum)+' doors');
    }
    return car;
})(); //<-- execute your module 

var DoorsClass = (function (){
    function doors(){ }
    doors.prototype.doors = function(num){
    return num;
    }
    return doors;
})();//<-- execute your module 

// Apply the given ctor with arguments.
var carInstance = applyCtor(CarClass,[new DoorsClass()]);
carInstance.color('red');
carInstance.doorsNum(4);

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

Destroy Three.js Renderer

Is there an effective method to properly destroy a three js instance? I am encountering an issue where removing the canvas and re-adding it results in two renderers being created. Presently, my approach involves: Removing all event listeners Cancellin ...

sending an array via xmlhttprequest

I am attempting to send all the marks entered by the user to another page for processing, but only the value of the first mark entered in the table is being sent. Is there a way to send all the values of the marks entered rather than just the first value ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Tips for displaying live data in the rows of Element UI's Table

Recently, I've been working with a table that looks like this. <v-table :data="data"> <v-table-column prop="data.attribute" label="Attribute"> </v-table-column> </v-table> Instead of displaying data.attribute in the co ...

What is the process for verifying your identity with Google OAuth2 in Vue.js?

Being new to vue.js, I have been struggling with a particular issue for days. Despite knowing that there are a few plugins available, such as: vue-google-auth and vue-google-signin-button and vue-authenticate Unfortunately, none of these plugins come ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

Transforming a jsonObject into a JavaScript array

I am working with a JSON object and I need to extract data from it to create an array. Here is an example of the desired array: ['city 1','city 2','city ..'] Below is the JSON output: {"\u0000*\u0000_data":[{"id": ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

Strategies for transferring all selected checkbox IDs to REST endpoint

I'm currently diving into web development and have set up a few checkboxes on my page. Right now, I have four checkboxes available. My goal is to send the IDs of the checkboxes that the user has checked to my "REST Service". Below is the code that I&a ...

Leveraging CreateBrowserRouter from React Router alongside a Redux store

I'm currently working on integrating Redux and React-Router into a React blog project. I am fetching data from an API and storing it in Redux, but for some reason, the data is not rendering and no error messages are being displayed. Here is the code ...

Can the lazy load script dependent on jQuery be utilized before the jquery.js script tag in the footer?

After receiving HTML from an AJAX callback, I noticed that there is a script tag for loading code that uses jQuery. However, I consistently encounter the error of jQuery being undefined. All scripts are connected before the closing </body> tag. Is ...

Attempting to format a number using a computed property and .toLocaleString() fails to execute

I am facing an issue with the formatting of a number displayed in a <p></p> element. The number is coming from a range input element that is bound to an amount data property using v-model. Even though I have a computed property to format the nu ...

Ways to automatically choose an option based on the value of another dropdown?

I need help with a dynamic dropdown feature. Essentially, I have three dropdown menus and I want the third one to update based on the selections made in the first two. For example, if "M" and "Red" are selected in the first two dropdowns, then the third dr ...

Is the MongoDB Query construction functioning properly in Node.js?

Struggling to construct a MongoDB query using OR and AND logic, where each OR word between keywords is placed in the Should block, and each AND word between words is placed in the must block. example - keyword1 OR keyword2 => both should be in the s ...

Issue with publishing npm package using yarn package manager

I'm currently in the process of releasing a fresh package. Utilizing ES6, I've been transpiling my files through babel to start with. However, I've hit a roadblock at this particular stage: https://i.stack.imgur.com/iIVp6.png This part se ...

Bring in content using transclusion, then swap it out using AngularJS

I am looking to develop a custom directive that will transform : <my-overlay class="someOverlay"> <h4>Coucouc</h4> </my-map-overlay> Into : <div class="someOverlay default-overlay"> <h4>Coucouc</h4&g ...

Issue-free AJAX call to Neo4j database on local server with no 'Access-Control-Allow-Origin' problem

I'm currently working on a basic JavaScript AJAX request to connect from a MAMP server running at localhost:8888 to a Neo4j database running on localhost:7474. The issue I'm encountering is the following error message: XMLHttpRequest cannot l ...

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Using angularjs ng-repeat in combination with owl-carousel

<div class="owl-carousel"> <div ng-repeat="items in itemlist"> <a href="series.html"><img ng-src="{{items.imageUrl}}" /></a> </div> <div> <a href="series.html><img src="http://p ...