谁能告诉我这种在 javascript 中模拟接口(interface)的方法是否正确?
$(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 方法是 duck typing .在松散类型的语言中,模拟接口(interface)应该不是必需的。
您的代码使事情复杂化了很多。此外,您应该以 UpperPascalCase
命名您的类,以 lowerCamelCase
命名您的变量名,这不是一个硬性规定,而是一个被广泛接受的约定,这将使您的代码更易于阅读对于其他人。
关于javascript - 在 Javascript 中模拟接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475458/