-1

I have a class like:

var TTable = function(name){  
  this.props= function(){
    this.properties=new TProperty();
    this.properties.Add("wfstart","Workflow start","L",false);
    this.properties.Add("wfend","Workflow end","L",false);
  }
  this.props(); 
}

I'd like to extend the TTable later with a new row of code in the props function like:

function addfeat(){
    //Add features
    var origprop = TTable.props;
    Reflect.defineProperty(TTable.prototype, 'props', { value: function() {
        origprop();
        this.properties.Add("ttype","Tipus","N",false);
    }});
}

So in my mind when I instantiate the TTable will be like this:

var TTable = function(name){  
  this.props= function(){
    this.properties=new TProperty();
    this.properties.Add("wfstart","Workflow start","L",false);
    this.properties.Add("wfend","Workflow end","L",false);
    this.properties.Add("ttype","Tipus","N",false);
  }
  this.props(); 
}

But the first code not working. Please help me.

  • What the OP actually might looking for is [JavaScript "method modification"](https://stackoverflow.com/search?tab=relevance&q=%5bjavascript%5d%20%22method%20modification%22) – Peter Seliger Sep 12 '22 at 14:02

1 Answers1

0

You're modifying TTable.prototype.props, but your class isn't actually using that prototype when it creates a props function for every instance. It shouldn't be doing that:

var TTable = function(name) { 
  this.props(); 
};
TTable.prototype.props = function() {
  this.properties = new TProperty();
  this.properties.Add("wfstart","Workflow start","L",false);
  this.properties.Add("wfend","Workflow end","L",false);
};

With this, your approach would actually work, given a few other fixes:

function addfeat(){
  // Add features
  var origprop = TTable.prototype.props;
//                     ^^^^^^^^^^
  TTable.prototype.props = function() {
//                       ^ assignment is sufficient, no need to `defineProperty`
    origprop.call(this);
//          ^^^^^^^^^^^ call as method on correct instance
    this.properties.Add("ttype","Tipus","N",false);
  };
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375