Object Oriented JavaScript with an Example

I know the general principles of object-oriented programming, such as encapsulation, inheritance, polymorphism, abstraction, etc.

But now I would like to understand these concepts from the point of view of JavaScript. Can someone take a very simple example and run how they work in the context of JS (encapsulation, inheritance, polymorphism, abstraction)

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

Thank.

+5
source share
4 answers

You can use the 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 below

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

new function(){...} does two things at once: define a function (an anonymous constructor function) and call it with a new one.

+4

, , - . . , . .

:

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
};

var instance = new MyClass(a, b);

:

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
};

JavaScript Duck Typing (http://en.wikipedia.org/wiki/Duck_typing). / , . , , newfangles.

- , - , , , , . , Javascript- .

, .

+20

, , .

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. 

-

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

  }

. fooobar.com/questions/881656/...

- , , "getFullName"

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

function(a){ a.getFullName() } , "" " ..", "".

Abstraction is a safer thing for the language. fooobar.com/questions/365784 / ...

+5
source

All Articles