最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

IS OOP possible in Javascript? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Aug 21, 2010 at 2:48 StarxStarx 79k50 gold badges186 silver badges265 bronze badges 3
  • 2 Javascript is an object oriented language; everything is an object. You thereby do object oriented programming with it whether you want to or not. Classes have surprisingly little to do with OOP. – deceze Commented Jul 23, 2013 at 9:14
  • Read the following blog post on why prototypal inheritance matters: aaditmshah.github.io/why-prototypal-inheritance-matters – Aadit M Shah Commented Jul 23, 2013 at 10:11
  • This question is similar to: Is JavaScript object-oriented?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – dumbass Commented Jan 29 at 19:06
Add a comment  | 

7 Answers 7

Reset to default 8

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.

OOP is central to Javascript, but it's not classical OOP. Javascript uses prototypes, not classes.

Douglas Crockford is a Javascript genius, so his Prototypal Inheritance in Javascript is a nice starting point. A Google search for "Javascript OOP" likely will turn up some neat articles to peruse, as well — I like the article by Mike Koss.

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/
  • http://msdn.microsoft.com/en-us/magazine/cc163419.aspx
  • http://www.dustindiaz.com/namespace-your-javascript/
  • http://vimeo.com/9998565

frameworks for oop js

  • http://jsclass.jcoglan.com/
  • http://www.prototypejs.org/

Pluralsight - JavaScript for C# Developers - Shawn Wildermuth - 2h 5m

  1. JavaScript Basics
  2. JavaScript Functions
  3. Object-Oriented JavaScript
  4. Practical Application

and

Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries - 356 pages -2008 -packed publishing

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.

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!

发布评论

评论列表(0)

  1. 暂无评论