用Javascript模拟接口
有人能告诉我这种用javascript模拟接口的方法是否正确吗用Javascript模拟接口,javascript,interface,Javascript,Interface,有人能告诉我这种用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.paymentInf
$(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');
});
}
});
});
});
这对我很有用,但如果有人能告诉我我是否错了,我会很高兴的。这方面的标准JavaScript方法是。在松散类型的语言中,不需要模拟接口
你的代码让事情变得复杂了很多。此外,你应该用
UpperPascalCase
命名你的类,用lowerCamelCase
命名变量名,这不是一条硬性规定,但这是一个被广泛接受的惯例,它会使你的代码更容易为他人阅读。好的,下次我发布一些代码时,我会记住你的建议。