IS OOP possible in Javascript?

2020-03-16 07:30发布

I recently found out that Javascript function can have classes, so I was wondering if OOP is also possible through javascript. Is It? If yes, Could you please point out some tutorials or site, where I can start with?

标签: javascript
7条回答
家丑人穷心不美
2楼-- · 2020-03-16 08:13

Javascript is an intrinsically OOP language. Like others have said, it is classless, but you have a choice of how you want to create objects.

You can create objects that make use of different types of inheritance.

  1. A pseudo-classical inheritance. Here you build constructor functions and use new to create classes. This will look most like the typical class based OOP.
  2. Prototypal inheritance. - This is what many of the other answer referred to.
  3. Functional inheritance. - In this mode you make use of closures, anonymous functions, and strategic returns to create truly private and protected variables.

There's a fair amount of cross over among these types. Suffice it to say that Javascript is a very flexible and powerful language for OOP.

I'm just learning about OOP in JS as well. Here is an example of functional inheritance I put together:

jsFiddle

// Object constructor
var parent = function (initial) {
    var that, privateNumber, hiddenVar; 
    that = {};    

    // Public variables
    that.share = initial - 32;

    // Public methods
    that.getNumber = function () {
        return privateNumber;                
    };

    // Private properties
    privateNumber = initial; 
    hiddenVar = "haha can't get me";    

    return that;
};

// Second object constructor that inherits from parent
var child = function (initial) {
    var that, privateName;

    // Inherit from parent
    that = parent(initial);

    // Public methods
    that.getName = function () {
        return privateName;                
    };

    // Private poroperties
    privateName = "Ludwig the " + initial + "th";

    return that;
};

// Create objects
var newPar1 = parent(42);
var newPar2 = parent(10);   

var newChild1 = child(0);
var newChild2 = child(100);

// Output on the jsFiddle page refed above: http://jsfiddle.net/ghMA6/
查看更多
冷血范
3楼-- · 2020-03-16 08:17

Here is an example of accomplishing an OO structure in javascript that is utilizing a library(not required, recommended)

//Create and define Global NameSpace Object
( function(GlobalObject, $, undefined) 
{
    GlobalObject.PublicMethod = function()
    {
        ///<summary></summary>
    }

    GlobalObject.Functionality = {}

}) (GlobalObject = GlobalObject || {}, jQuery);

//New object for specific functionality
( function(Events, $, undefined)
{
    //Member Variables 
    var Variable; // (Used for) , (type)

    // Initialize
    Events.Init = function()
    {
        ///<summary></summary>
    }

    // public method
    Events.PublicMethod = function(oParam) 
    {
        ///<summary></summary>
        ///<param type=""></param>
    }

    // protected method (typically define in global object, but can be made available from here)
    GlobalObject.Functionality.ProtectedMethod = function()
    {
        ///<summary></summary>
    }

    // internal method (typically define in global object, but can be made available from here)
    GlobalObject.InternalMethod = function()
    {
        ///<summary></summary>
    }

    // private method
    var privateMethod = function()
    {
        ///<summary></summary>
    }

    Events.PublicProperty = "Howdy Universe";
}) (GlobalObject.Functionality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )

// Reusable "class" object
var oMultiInstanceClass = function()
{
    // Memeber Variables again
    var oMember = null; // 

    // Public method
    this.Init = function(oParam)
    {
        oMember = oParam;
    }
}

The strength to this is that it initializes the Global object automatically, allows you to maintain the integrity of your code, and organizes each piece of functionality into a specific grouping by your definition.

This structure is solid, presenting all of the basic syntactical things you would expect from OOP without the key words.

There are even some ingenious ways to set up interfaces as well. If you choose to go that far, a simple search will give you some good tutorials and tips.

Even setting up intellisense is possible with javascript and visual studio, and then defining each piece and referencing them makes writing javascript cleaner and more manageable.

Using these three methods as needed by your situation helps keep the global namespace clean, keep your code organized and maintains separation of concerns for each object.. if used correctly. Remember, Object Oriented Design is of no use if you don't utilize the logic behind using objects!

查看更多
叛逆
5楼-- · 2020-03-16 08:23

Yes. It is possible. I have ever using the Script# to build javascript application, It allow you writing C# code, and translate to JavaScript. it is an good experience, especially for large project, it will force your thinking in the OOP way to order your code.

The tool can be found at: (it is open source but write by an Microsoft employee) http://scriptsharp.com

If you are not familiar with C# you can also find the similar tool for writing javascript in Java.

And if you don't want to using those too, you can investigate how it convert the code to understand how it implement the OOP feature.

查看更多
混吃等死
7楼-- · 2020-03-16 08:27

OOP is definitely possible. While Javascript doesn't have "classes" like most OO languages do, what it does have is called "prototypes". Basically, objects are defined in terms of other objects rather than classes. (Objects can also emulate classes to some degree, for those who can't wrap their minds around prototypal inheritance.)

One could argue JS's OO capabilities exceed those of most languages, considering objects play an even more essential role than in languages with classes.

查看更多
登录 后发表回答