Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object oriented JavaScript with example [closed]

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.

like image 505
copenndthagen Avatar asked Feb 20 '13 05:02

copenndthagen


1 Answers

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.

like image 163
Gregory Magarshak Avatar answered Sep 20 '22 00:09

Gregory Magarshak