Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding property in JavaScript function

Tags:

javascript

web

I want to override a member function in constructor function not the whole constructor function but only one member function inside it, my constructor function look like

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");
          }
      };
  }

and in override.js i want to override it like this

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

and when i create object of viewModel constructor function

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

then output should be you are in overrided function test funcA, but it print you are in not overrided function test FuncA which is not my desire output how may i achieve desire output.

When only core.js file is loaded in my web page then the testFuncA will output as you are in not overrided function test FuncA but when i load both files, that is core.js and after that override.js then testFuncA will output you are in overrided function test funcA.

like image 356
Mansoor Akhtar Avatar asked Dec 27 '25 23:12

Mansoor Akhtar


1 Answers

So first off, we cannot change the inner workings of this constructor function, you can only do that sort of thing with a prototype, so instead you will need to completely override it in the namespace. In override.js simply have the same code like this:

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");
    };
}

So this will replace your original function in the namespace, ultimately achieving your goal. Had you been using a prototype system where you copy from an existing object, you'd simply have to do something along the lines of Proto.testFuncA = function(){...}

Note: I changed the code as a suggestion on how to handle your constructors, as a constructor is passed a new object via 'this' already, no need to make another. You also had 'Self' as a reference to 'this' but then by making a new object you actually only changed the reference in Self to the new object, you did not actually alter this in any way. instead you altered this new object that 'Self' was pointing to.

Note2: So if you would like to use prototypes. I would read through this Why is it necessary to set the prototype constructor? for a better understanding of prototypes. And this as well http://www.w3schools.com/js/js_object_prototypes.asp

like image 156
Sean_A91 Avatar answered Dec 30 '25 12:12

Sean_A91



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!