This question already has answers here:
Dynamically access object property using variable
(16个答案)
6年前关闭。
我想传递一个函数名称(update1或update2或update3)来更新函数
输出应为:
这就是您应该如何调用名称作为参数
编辑:http://jsfiddle.net/x8jwavje/1/
(16个答案)
6年前关闭。
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;
最佳答案
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/