如何将原型函数名称传递给另一个原型函数

How to pass a prototype function name to another prototype function

本文关键字:原型 函数 另一个      更新时间:2023-09-26
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')

我想传递函数名称(update1 或 update2 或 update3)来更新函数

输出应为:updated tyres with update1;

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')

这就是您应该如何调用其名称作为参数传递的函数this[updateFn]( s)

编辑:http://jsfiddle.net/x8jwavje/1/