我正在定义一个叫做Validator的函数。在此范围内,我将this.luhn定义为另一个函数。现在,如果引擎参数被传递给Validator函数,并且引擎函数存在于Validator中,那么我想运行它。在这一点上,我得到了“引擎的方法卢恩找不到”在我的日志。
代码:
var Validator = (function( cardnumber, cardtype, engine ){
this.cardnumber = cardnumber;
this.cards = {"mastercard":"51,52,53,54,55", "visa":"4"};
this.luhn = (function( cardnumber ){
var len = cardnumber.length,
mul = 0,
prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
sum = 0;
while (len--) {
sum += prodArr[mul][parseInt(cardnumber.charAt(len), 10)];
mul ^= 1;
}
return sum % 10 === 0 && sum > 0;
});
if( typeof this.engine != "undefined" ){
this.engine();
}
else {
console.log( "Engine for method " + engine + " not found" );
}
});我是如何发起的:
var test = new Validator( '4861224212948679', 'visa', 'luhn' );如果luhn是在"this“中定义的,谁能指出正确的方向来敲击luhn(或任何其他函数)?
发布于 2014-10-21 07:45:00
使用括号符号代替:
if (typeof this[engine] === 'function') {
this[engine](cardnumber);
}..。我宁愿在这里选择engineName,而不是engine (传递函数的名称,而不是函数本身)。说到这些,我不得不说,我可能更倾向于放弃这种方法,而改用方法注入:在其他地方定义luhn函数,直接将它传递给Validator构造函数。
function luhn(cardnumber) { ... }
// inside Validator function
if (typeof engine === 'function') {
engine(cardnumber);
}
var validator = new Validator('5555...', 'Mastercard', luhn);https://stackoverflow.com/questions/26481291
复制相似问题