【问题标题】:Simulating Interfaces in Javascript用 Javascript 模拟接口
【发布时间】:2014-08-19 23:00:44
【问题描述】:

谁能告诉我这种在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');
      });  
    }
  });
});
});

这对我有用,但如果我错了,如果有人能告诉我,我会很好。

【问题讨论】:

    标签: javascript interface


    【解决方案1】:

    标准的 JavaScript 方式是 duck typing。模拟接口不应该是松散类型语言的必要条件。

    您的代码使事情复杂化了很多。此外,你应该用UpperPascalCase 命名你的类,用lowerCamelCase 命名变量名,这不是一个硬性规则,而是一个被广泛接受的约定,它会让你的代码更容易被其他人阅读。

    【讨论】:

    • 好的,下次我发布一些代码时,我会考虑您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多