5

I am aware of general Object-oriented programming principles like Encapsulation, Inheritance, Polymorphism, Abstraction, etc

But would now want to understand these concepts from a JavaScript perspective. Could someone take a very basic example and run how these works in JS context (Encapsulation, Inheritance, Polymorphism, Abstraction)

I have read a lot about these online, but the articles have left me more confused.

Thank you.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • Why don't you find a problem you're interested in, and see if you can solve it using these techniques and then come back if you have specific technical issues. Some of these concepts are not so important, or implemented differently in JS compared to languages like c++. – Aesthete Feb 20 '13 at 05:06
  • You should go through the articles again at a slower pace. Absorbing things slowly tends to reduce confusion. That said, I'm voting to close this question, since tutorial requests are off topic on Stack Overflow. – Asad Saeeduddin Feb 20 '13 at 05:10
  • You should read about the differences between classes and prototypes. For example a good answer talks about classic inheritance and prototypal inheritance : http://stackoverflow.com/a/186279/1068746. Once you get prototypes properly, the rest is a piece of cake. – guy mograbi Feb 20 '13 at 05:55

3 Answers3

20

I will describe the Douglas Crockford Pattern to mimic the style used in Object-Oriented Programming languages. It doesn't use prototypal inheritance. As a result, it's slightly less efficient because each object has to store a reference to each method. But it's very useful for illustrative purposes.

Encapsulation:

function MyClass (a, b)
{
    this.publicProperty = 1;
    var _privateProperty = 2;
    function _privateMethod () {
        // only private methods and privileged methods can call this
    };
    this.publicMethod = function () {
        // can access _privateProperty and call _privateMethod
    };
}
MyClass.classMethod = function () {
    // not tied to any instances
};

Simply create objects with var instance = new MyClass(a, b);

Inheritance:

function DerivedClass(a, b, c) 
{
    // must explicitly call superclass constructor, like in Java
    MyClass.apply(this, arguments);

    this.anotherProperty = 3;
    function _anotherPrivateMethod() { };

    this.publicMethod = function () {
        // can access _privateProperty and call _privateMethod
    };
}
DerivedClass.classMethodMethod = function ()
{
    // not tied to any instances
};

Polymorphism in JavaScript is mostly replaced by Duck Typing (http://en.wikipedia.org/wiki/Duck_typing). Developers usually group methods/properties under objects, and you just test for the presence of those objects. This is how newfangles browser capabilities are detected, for instance.

Abstraction is closely tied with the polymorphism - as long as something supports an interface, you don't usually care how it works underneath. Thus, you may download a Javascript library and just use it, based on its documentation.

Hope this helps.

Gregory Magarshak
  • 1,883
  • 2
  • 25
  • 35
  • 1
    +1: this is what I was looking for: a simple example describing private/public properties/methods and inheritance for OOJS. – sp00m Jun 14 '13 at 07:43
5

I think the most interesting is encapsulation as a lot of people don't use it properly.

Lets take a simple object as an example

var Person = function( firstName, lastName, isMr ) {
    var prefix = isMr ? "Mr." : "Mrs." ; 
    this.getFullName = function() { return prefix + " " 
                                       + firstName + " " + lastName }

}

 var p = new Person ("guy","mograbi", true);
 p.getFullName(); // => "Mr. guy mograbi"
// p.prefix ==> causes an error. 

Inheritance - is simply extending the prototype

 var Superhero = function(){
            Person.call(this);

  }

However proper inheritance is an issue by itself. Check out https://stackoverflow.com/a/4985616/1068746

Polymorphism - is quite simple, given a new prototype that implements "getFullName"

var Child = function(){
    this.getFullName = function(){ return "not allowed to talk with strangers" }
}

given function(a){ a.getFullName() } You will get full name if a is Person and "not allowed.." if a is Child.

Abstraction - is more of a type-safe language thing. https://stackoverflow.com/a/4082496/1068746

Community
  • 1
  • 1
guy mograbi
  • 27,391
  • 16
  • 83
  • 122
  • Thx a lot for that...Will it be possible for u to add more details to the same..like when u give the example for encapsulation, can u say where exactly is encapsulation happening ? Also in case u can explain Inheritance/Polymorphism in more detail with simple examples? – copenndthagen Feb 20 '13 at 06:47
4

You can use a function to define a singleton object

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

use it as given below

apple.color = "reddish";
alert(apple.getInfo());

new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ankush Jain
  • 1,532
  • 1
  • 15
  • 24