How to protect the functions called with different contexts of the break?

advertisements

I'm fairly new to javascript and now I learned how calling functions with a context works.

Here is a simple example that poses a question in my head. Lets say we have this example:

var myObj = {
    bar: function() {
      console.log("Lets got to the bar!");
    }
}

/* how can this be protected from errors,
 * if a passed object doesn't contain bar */
function foo()
{
   this.bar();
} 

foo.call(myObj);

Now, how can foo be protected of breaking? In some OOP language (lets say Java) this would be implemented lets say via an interface. So in that case if the object being instantiated hasn't implemented the interface method, the compiler would through an error so the compiler protects the code/program from being faulty (in this case of course).

public interface MyInterface
{
   public void bar();
}

public class MyClass implements MyInterface
{
   public void bar()
   {
     System.println("Lets go to the bar");
   }
}

MyInterface m = new MyClass();
m.bar(); // if bar isn't implemented the compiler would warn/break

Note: I'm not that good in Java so sorry for any syntax or other errors, but I hope you get the point.

So to sum up, as I see that in both cases in both languages one can achieve polymorphism, right? Now if so for the Javascript example, how can one protect it from breaking, are there any patterns or tricks? Does typeof this.bar === function work? If so, who guarantees the SW quality if the programmer forgets this, I'm asking this kind of question because Java has the compiler to warn the programmer about the mistake, does JS have something similar, some quality check tool?


Javascript is a dynamic interpeted* language. There isn't a compiler step to check references. Some tools (jsline) and IDEs (VS, Webstorm) can perform some design-time checks for you, but there's no true type safety. This is largely seen as a feature, not a bug.

There's an array of tricks to work around this (.hasOwnProperty, typeof x === 'function', storing self references, context binding) but mostly, if you want a type safety, you want a different language.

My recommendation is Typescript. It has a Java/C-like syntax, with some familiar OOP features, like classes, interface (and thus, sane polymorphism) and generic types, and transpiles to javascript in moments.