JavaScript function with property overriding

I am looking to modify a specific member function within a constructor function without affecting the entire constructor. Here is an example of my current constructor function:

function viewModel(){
  var self= this;
  self = {
          testFuncA:function(){
            console.log("you are in not overrided function test FuncA");
          },
          testFuncB:function(){
            console.log("you are in not orverided function test FuncB");
          }
      };
  }

In the file override.js, I want to override it like so:

viewModel.prototype.testFuncA = function(){
      console.log("you are in overrided function test funcA");  
 }

When creating an object of the viewModel constructor function:

var obj = new viewModel();
obj.testFuncA();

The desired output should be you are in overrided function test funcA. However, currently it prints you are in not overrided function test FuncA. How can I achieve the desired output?

When only the core.js file is loaded on my web page, the testFuncA will output as you are in not overrided function test FuncA. But when both files are loaded - first core.js and then override.js - then testFuncA will output you are in overrided function test funcA.

Answer №1

To start with, it's important to note that the inner workings of this constructor function cannot be changed directly; changes can only be made through a prototype. In order to achieve your desired outcome, you will have to completely override it within the designated namespace. In the file override.js, simply include similar code like the following:

function viewModel(){
    this.testFuncA = function(){
        console.log("This is an overrided function test FuncA");
    };
    this.testFuncB = function(){
        console.log("This is an function test FuncB");
    };
}

This will effectively replace the original function in the namespace and accomplish your goal. If you were using a prototype system where you replicate from an existing object, you would just need to something akin to Proto.testFuncA = function(){...}

Note: I have modified the code as a suggestion on how to manage your constructors. A constructor already receives a new object via 'this', so there is no necessity for creating another one. The reference to 'Self' was altered to point to the new object, not changing 'this' itself. Instead, modifications were made to the new object that 'Self' was referencing.

Note2: If you prefer to utilize prototypes, I recommend reading through Why is it necessary to set the prototype constructor? for a deeper comprehension of prototypes. Additionally, check out http://www.w3schools.com/js/js_object_prototypes.asp

Answer №2

If you come across a scenario similar to the one below in core.js

      function viewModel(){
      }
      viewModel.prototype.testFuncA = function(){
        console.log("you are in not overrided function test FuncA");
      };
      viewModel.prototype.testFuncB = function(){
        console.log("you are in not orverided function test FuncB");
      };

You can then create an override.js file with something like this

      viewModel.prototype.testFuncA = function(){
            console.log("you are in overrided function test funcA");  
       }

Updated approach: if you prefer not to modify core.js.

var viewModelParent = viewModel;
var myViewModel = new viewModelParent();

var viewModel = function(){
    this.testFuncA = function(){
            console.log("you are in overrided function test funcA");  
    }
};
viewModel.prototype = myViewModel;

Answer №3

core.js has the ability to make changes like:

function viewModel(){

}
viewModel.prototype = {
      testFuncA:function(){
        console.log("you are in not overrided function test FuncA");
      },
      testFuncB:function(){
        console.log("you are in not orverided function test FuncB");
      }
}

To override the function in override.js, use the following code:

viewModel.prototype.testFuncA=function(){
     //TODO::
}

Ensure that core.js is loaded before override.js.

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

When it comes to HTML and Javascript, there is a distinct contrast between an ajax call and altering the content of an

I am currently working on coding a JavaScript function to allow liking a specific post on Tumblr. I came across this helpful resource for reference. Initially, I attempted using an ajax call instead of modifying the source of an iframe, but unfortunately, ...

What is the best way to input variables into json values? [JavaScript]

let countryCode; let countryName; $(window).on("load", function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" }).done(function (json) { countryCode = json.country_code; $(function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" ...

Vue.js powered search bar for exploring countries worldwide (utilizing the restcountries API)

Despite successfully loading the API country data (as evidenced by the console.log() entry and the accompanying picture of my work desk), the country information does not display when hovering the mouse cursor over the search bar field (expecting a dropdow ...

Ensuring Package Security in NodeJS and NPM

Given the immense popularity of NodeJS and how NPM operates, what measures can be taken to prevent the installation of insecure or malware-laden packages? Relying solely on user feedback from sources like StackOverflow or personal blogs seems to leave a si ...

Halt the execution of JavaScript code

I'm having trouble making this conditional if statement work properly... The line " if ( !$section.id == "no-transition" ) " seems to be incorrect. My goal is to prevent JavaScript from executing on sections with the id "no-transition". Could someo ...

The Strophe.muc plugin and backbone improper binding of callbacks

Following the initial group message, I'm experiencing an issue with the strophe.muc plugin not responding to subsequent messages. Although I receive the first presence, message, and roster from the room, any additional messages and presence stanzas do ...

AngularJS Login Popup with SpringSecurity

I have successfully integrated spring security with my AngularJS webpage utilizing Rest API. However, I am facing an issue where every time I attempt to log in using the rest api from my customized login page, it prompts me for the login credentials in a p ...

Firebase - accessing the most recent entry

I have a node server up and running where I need to monitor updates in a collection and retrieve the newly added data. My approach was to utilize db.collection("posts").onSnapshot to listen for updates and fetch the latest entry by ordering it ba ...

Invoking Redux actions within a React component

I'm attempting to send a variable to a Redux action, however, it seems that the action is receiving undefined. What could be causing this issue? index.js - location of action invocation import React from 'react' import { connect } from &ap ...

Transfer a value to the ng2 smart table plugin extension

Upon reviewing the document and source code related to pagination implementation in the (advanced-example-server.component.ts), I discovered that the ServerDataSource being used only supported pagination through HTTP GET (_sort, _limit, _page, etc paramete ...

A step-by-step guide on extracting the image source from a targeted element

Here is a snippet of my HTML code containing multiple items: <ul class="catalog"> <li class="catalog_item catalog_item--default-view"> <div class="catalog_item_image"> <img src="/img/01.png" alt="model01" class="catalog_it ...

What are the various undisclosed schema types in A-Frame?

I've been exploring different examples of property types in the official documentation and various Github repositories (though now I can't remember which ones). The latter introduced me to unique properties like "min" and "max" for numbers, as we ...

ngModel and ngRepeat allow for easy manipulation and iteration of properties

Here is a sample HTML code: <div ng-repeat="item in items()"> <input type="checkbox" ng-model="anObject[item.name]"> </div> I am trying to access a property that depends on the item.name within my $scope.anObject which I defined in ...

Check to see if a guest has shown support or followed an outside party

When you already follow a company on Twitter, the "Follow Us" button of that company will automatically turn grey, regardless of the domain. So, how can you determine if User-X is following companies A, B, and/or C based on their Twitter handles? The same ...

Syntax in Next.js for shallow routing

When working with next js, I want to update the route without refreshing the page. Currently, I am using the following syntax which I find cumbersome: Router.push( `/statistics?entityId=${id}&type=${entityType}&provider=${serviceProvider}`, ...

Scrolling to a specific position on a page when a Vue 3 component appears is a must-do for

When I click a button, my basic form component appears without using the router. I would like the scroll position of the form to automatically move down slightly (for example, on the y-axis at 40) once it is displayed. However, I am unsure of how to achi ...

Risks associated with the use of Base64 encoded URLs in relation to security

When accessing my API from a web application, I'm using ajax to send get and post requests. Since I'm new to this, I'm curious about the security implications related to the content type being used. Currently, I know of two content types t ...

Transforming date and timezone offset into an isoDate format using moment.js

When retrieving data from the API, I encounter Date, Time, and Offset values in separate columns. My goal is to obtain an ISO date while maintaining the original date and time values. const date = "2019-04-15" const time = "13:45" const ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...