How to pass prototype function name to another prototype function

function car() {
}

car.prototype = {
 update1: function(s) {
   console.log("updated "+s+" with update1")
 },
 update2: function(s) {
   console.log("updated "+s+" with update2")
 },
 update3: function(s) {
   console.log("updated "+s+" with update3")
 },
 update: function(s, updateFn) {
   this.updateFn.call(this, s)
 }
}

var c = new car()

c.update("tyres", 'update1')

      

I want to pass the function name (update1 or update2 or update3) to update the function

the output should be: updated tyres with update1;

+3


source to share


1 answer


http://jsfiddle.net/x8jwavje/

 function car() {
    }

car.prototype = {

 update1: function(s) {
   console.log("updated "+s+" with update1")
 },
 update2: function(s) {
   console.log("updated "+s+" with update1")
 },
 update3: function(s) {
   console.log("updated "+s+" with update1")
 },
 update: function(s, updateFn) {

   this[updateFn]( s)
 }
}

var c = new car()

c.update("tyres", 'update1')

      



so you have to call the function whose name is passed as parameter this[updateFn]( s)

Edit: http://jsfiddle.net/x8jwavje/1/

+3


source







All Articles