2014-11-27 4 views
3
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;

+1

У вас не может быть несколько свойств 'update1' в одном и том же объекте. – Barmar

+2

'this [updateFn] .call (это, s)' – Barmar

+0

извините, скопируйте ошибку папы –

ответ

3

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/

Смежные вопросы