3

Anybody could tell me if this way of simulating interfaces in javascript is correct?

$(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');
      });  
    }
  });
});
});

It works to me but I will great if anybody can tell me If I'm wrong.

1 Answer 1

2

The standard JavaScript way for this is duck typing. Simulating interfaces should not be necassary in a loosely typed language.

Your code is complicating matters, a lot. Besides, you should name your classes in UpperPascalCase and variable names in lowerCamelCase, this is not a hard rule, but is a widely accepted convention that will make your code easier to read for others.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, i will have your recommendations in mind the next time I post some code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.