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.

3
  • 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++. Commented Feb 20, 2013 at 5: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. Commented Feb 20, 2013 at 5:10
  • You should read about the differences between classes and prototypes. For example a good answer talks about classic inheritance and prototypal inheritance : stackoverflow.com/a/186279/1068746. Once you get prototypes properly, the rest is a piece of cake. Commented Feb 20, 2013 at 5:55

3 Answers 3

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.

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

1 Comment

+1: this is what I was looking for: a simple example describing private/public properties/methods and inheritance for OOJS.
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

1 Comment

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?
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.

4 Comments

apple isn't a class (or constructor function, since there aren't technically any classes in JS), it is an instance of an anonymous constructor function.
What is the point of using new here in front of the function?
@jfriend00 Instantiates the function, returning {type: "macintosh", color: "red", getInfo: function(){...}}
@Asad - why not just define the object you want then?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.