任何人都可以告诉我这种在javascript中模拟接口的方式是否正确?
$(document).on('ready', function(){
//Simulating Interfaces in Javascript using Functions with Call
var IPayable = function(){
this.payAmount = null;
this.payment = function(fn){return fn(this);};
this.paymentInform = function(fn){return fn(this);};
};
var IAlertable = function(){
this.maxPayAmount = null;
this.maxExceeded = function(fn){return fn(this);};
};
var User = {userName: 'Adam'};
//Assigning the Interfaces
IPayable.call(User);
IAlertable.call(User);
User.payment(function(User){ //Using the first function of IPayable
User.payAmount = 100; //Update the amount for later use
User.maxPayAmount = 30; //Update the maximum you cannot exceed
User.maxExceeded(function(User){ //Using the IAlertable
if(User.payAmount > User.maxPayAmount){
console.log(User.userName + ' your max was exceeded ' +
(User.payAmount - User.maxPayAmount + '$'));
}else{
console.log(User.userName + ' has made a payment of: ' + User.payAmount + '$');
User.paymentInform(function(User){ //Using the seconf function of IPayable
console.log('Your payment of '+ User.payAmount +'$ was made');
});
}
});
});
});
这对我有用但如果有人能告诉我,如果我错了,我会很高兴。
答案 0 :(得分:2)
标准的JavaScript方式是duck typing。在松散类型的语言中,模拟接口不应该是必需的。
你的代码很复杂。此外,您应该在UpperPascalCase
中命名您的类,在lowerCamelCase
中命名变量名称,这不是一个很难的规则,但是这是一个广泛接受的约定,它将使您的代码更容易为其他人阅读。