Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Patterns - Difference between the Facade and Object literal pattern

I'm wondering what's the difference between these two patterns.

I may be mistaken but they seem to be using the same structure to achieve a higher-level interface to a larger body of code.

Facade Pattern:

var mobileEvent = {
  // ...
  stop: function (e) {
    e.preventDefault();
    e.stopPropagation();
  }
  // ...
};

Object Literal:

var myObject = {
    property1:"something",
    property2:"something else",
    method1:function(){
        console.log('hello world');
    }
};

If they really serve different purposes, when should I use them exactly?

like image 795
Frank Parent Avatar asked Feb 16 '26 20:02

Frank Parent


1 Answers

Just the fact that they use the same syntax does not mean they have same purpose. Many design patterns have exactly the same implementation but have different meaning based on the context.

Facade encapsulates one or more objects and provides easier API for the client, hiding the obscurities and making it harder to make a mistake. In your example mobileEvent.stop() function encapsulates two JavaScript calls that have to go together in order to achieve some higher level behaviour.

Object literal isn't really a pattern, it is just a way to define one-time object in JavaScript. As you can see it can be used to implement Facade pattern and many others.

like image 62
Tomasz Nurkiewicz Avatar answered Feb 18 '26 08:02

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!