用 Javascript 进行 OOP 编程 - 正确

发布于 2024-11-03 22:33:41 字数 1033 浏览 2 评论 0原文

我对改进我的 javascript 代码以使其成为适当的 OOP 很感兴趣......目前我倾向于做这样的事情:

jQuery(document).ready(function () {
    Page.form = (function () {
        return {
            //generate a new PDF
            generatePDF: function () {

            },
            //Update the list of PDFs available for download
            updatePDFDownloads: function () {

            },
            /*
             * Field specific functionality
             */
            field: (function () {
                return {
                    //show the edit prompt
                    edit: function (id, name) {

                    },
                    //refresh the value of a field with the latest from the database
                    refresh: function (id) {

                    }
                };
            }())
        };
    }());
});

我想最后它只是主要组织的函数......有什么好的资源可以让我学习如何对 javascript 进行编程以面向对象的方式,或者您对改进我当前的编程风格有何建议?

看来我应该做一种模型原型,并让我的 form 对象从该原型继承。

(由于与prototypeJS冲突,我使用jQuery而不是$)

I'm interesting in improving my javascript code to be properly OOP.... currently I tend to do something like this:

jQuery(document).ready(function () {
    Page.form = (function () {
        return {
            //generate a new PDF
            generatePDF: function () {

            },
            //Update the list of PDFs available for download
            updatePDFDownloads: function () {

            },
            /*
             * Field specific functionality
             */
            field: (function () {
                return {
                    //show the edit prompt
                    edit: function (id, name) {

                    },
                    //refresh the value of a field with the latest from the database
                    refresh: function (id) {

                    }
                };
            }())
        };
    }());
});

In the end it's just mainly organized functions I suppose... what's a good resource where I can learn to program javascript in an OOP manner, or what suggestions would you have for improving my current style of programming?

It seems like I should do a sort of model prototype and have my form object inherit from that prototype.

(I'm using jQuery instead of $ because of conflicts with prototypeJS)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

夜血缘 2024-11-10 22:33:41

您的问题非常广泛,因此我认为这里不可能给出完整的答案。但这里有几点。

关于您所显示的代码。你正在跳几个多余的圈。

  1. 除非您以某种方式访问​​ DOM,否则无需将代码包装在 jQuery(document).ready() 中。
  2. 无需从自调用匿名函数返回对象,除非你关闭了一些私有函数或数据

你创建的对象可以像这样更简单地创建(一件好事)

var Page = {
    form: {
        //generate a new PDF
        generatePDF: function () {

        },
        //Update the list of PDFs available for download
        updatePDFDownloads: function () {

        },
        /*
        * Field specific functionality
        */
        field: {
            //show the edit prompt
            edit: function (id, name) {

            },
            //refresh the value of a field with the latest from the database
            refresh: function (id) {

            }
        }
    }
};

它更容易阅读并且不那么混乱,只做那些能给你带来东西的事情。请参阅 cargo cult 编程

这是一个使用自调用匿名函数来创建私有成员的示例

var Obj = (function() {
    privateFunction( param ) {
        // do something with param
    }

    var privateVar = 10;

    return {
        // publicMethod has access to privateFunction and privateVar
        publicMethod: function() {
            return privateFunction( privateVar );
        }
    }

})();

您拥有的结构正如您所说,使用对象文字非常适合对一组函数(方法)和属性进行分组。这是一种命名空间。它也是创建单例的一种方法。您可能还想创建同一类的许多对象。
JavaScript 没有像传统面向对象语言那样的类(我会讲到),但在最简单的层面上,创建一个“模板”来创建特定类型的对象是非常容易的。这些“模板”是称为构造函数的普通函数。

// a constructor
// it creates a drink with a particular thirst quenchingness
function Drink( quenchingness ) {
    this.quenchingness = quenchingness;
}

// all drinks created with the Drink constructor get the chill method
// which works on their own particular quenchingness
Drink.prototype.chill = function() {
   this.quenchingness *= 2; //twice as thirst quenching
}

var orange = new Drink( 10 );
var beer   = new Drink( 125 );

var i_will_have = ( orange.quenchingness > beer.quenchingness ) 
    ? orange 
    : beer; //beer

var beer2  = new Drink( 125 );
beer2.chill();

var i_will_have = ( beer2.quenchingness > beer.quenchingness )
    ? beer2 
    : beer; //beer2 - it's been chilled!

关于构造函数有很多东西需要了解。你必须四处寻找。 SO 上有很多例子。
继承是面向对象的基础,但在 js 中并不那么直观,因为它是原型的。我不会在这里讨论这个,因为你很可能不会直接使用 js 的原生原型继承范例。
这是因为有些库可以非常有效地模仿经典继承,原型(继承)mootools(类) 其他

许多人说继承在面向对象中被过度使用,并且您应该支持组合,这让我想到了我的观点当我开始这个漫无目的的答案时,最初就打算推荐。

JavaScript 中的设计模式与任何 OO 语言中的设计模式一样有用,您应该熟悉它们

我建议您阅读 专业 JavaScript 设计模式
在那里,就是这样

Your question is quite broad so I don't think a complete answer is possible here. But here are a few points.

Regarding the code you have shown. You're jumping a couple of redundant hoops.

  1. Unless you're accessing the DOM in some way, there is no need to wrap your code in jQuery(document).ready()
  2. There is no need to return an object from a self calling anonymous function unless you're closing over some private functions or data

The object you have created can be created more simply (a good thing) like this

var Page = {
    form: {
        //generate a new PDF
        generatePDF: function () {

        },
        //Update the list of PDFs available for download
        updatePDFDownloads: function () {

        },
        /*
        * Field specific functionality
        */
        field: {
            //show the edit prompt
            edit: function (id, name) {

            },
            //refresh the value of a field with the latest from the database
            refresh: function (id) {

            }
        }
    }
};

It's easier to read and less confusing, only do things that buy you something. see cargo cult programming

Here's an example using a self calling anonymous function to create private members

var Obj = (function() {
    privateFunction( param ) {
        // do something with param
    }

    var privateVar = 10;

    return {
        // publicMethod has access to privateFunction and privateVar
        publicMethod: function() {
            return privateFunction( privateVar );
        }
    }

})();

The structure you have used, object literals are very good, as you say, at grouping a set of functions (methods) and properties. This is a kind of namespace. It is also a way of creating a Singleton. You may also want to create many objects of the same Class.
JavaScript doesn't have classes like traditional OO languages (I'll get to that) but at the simplest level it's very easy to create a 'template' for creating objects of a particular type. These 'templates' are normal functions called constructors.

// a constructor
// it creates a drink with a particular thirst quenchingness
function Drink( quenchingness ) {
    this.quenchingness = quenchingness;
}

// all drinks created with the Drink constructor get the chill method
// which works on their own particular quenchingness
Drink.prototype.chill = function() {
   this.quenchingness *= 2; //twice as thirst quenching
}

var orange = new Drink( 10 );
var beer   = new Drink( 125 );

var i_will_have = ( orange.quenchingness > beer.quenchingness ) 
    ? orange 
    : beer; //beer

var beer2  = new Drink( 125 );
beer2.chill();

var i_will_have = ( beer2.quenchingness > beer.quenchingness )
    ? beer2 
    : beer; //beer2 - it's been chilled!

There's a lot to know about constructors. You'll have to search around. There are lots of examples on SO.
Inheritance, the foundation of OO, is not that intuitive in js because it is prototypal. I won't go into that here because you will more than likely not use js's native prototypal inheritance paradigm directly.
This is because there are libraries that mimic classical inheritance very effectively, Prototype (inheritance) or mootools (Class) for example. There are others.

Many say that inheritance is overused in OO and that you should favour composition and this brings me to what I initially set out to recommend when I started this rambling answer.

Design patterns in JavaScript are as useful as in any OO language and you should familiarise yourself with them

I recommend you read Pro JavaScript Design Patterns.
There, that's it

眼眸里的那抹悲凉 2024-11-10 22:33:41

没有一种正确的方法......有些人使用框架来定义他们的对象,我喜欢直接扩展原型。不管怎样,我想说 Oran Looney 有一些关于 JS 中的 OO 机制的好帖子:

http:// /oranlooney.com/classes-and-objects-javascript/

也值得看看他的其他文章:

http://oranlooney.com/deep-copy-javascript/
http://oranlooney.com/function-javascript/

There isn't one correct way... Some people use a framework to define their object, I like to just extend prototype directly. Anyhow, I wanted to say that Oran Looney has some good posts on OO mechanics in JS:

http://oranlooney.com/classes-and-objects-javascript/

Its also worth looking at his other articles:

http://oranlooney.com/deep-copy-javascript/
http://oranlooney.com/functional-javascript/

天生の放荡 2024-11-10 22:33:41

我们使用的代码遵循这个基本结构:

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

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

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

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

    // public method
    this.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>
    }
}) (GlobalObject.Funcitonality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )

这样做的优点是它自动初始化 Global 对象,允许您维护代码的完整性,并根据您的定义将每个功能组织到特定的分组中。这个结构很扎实,呈现了您期望从 OOP 中获得的所有基本语法内容,而无需关键字。甚至可以使用 javascript 设置智能感知,然后定义每个部分并引用它们使得编写 javascript 更干净且更易于管理。希望这个布局有帮助!

The code we are using follows this basic structure:

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

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

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

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

    // public method
    this.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>
    }
}) (GlobalObject.Funcitonality.Events = GlobalObject.Funcitonality.Events || {}, jQuery )

The strength to this is that it initializes the Global object automatically, allows you to maintain the intergrity 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. Even setting up intelisense is possible with javascript, and then defining each peice and referencing them makes writing javascript cleaner and more manageable. Hope this layout helps!

寄人书 2024-11-10 22:33:41

我认为你使用什么语言并不重要,好的 OOP 就是好的 OOP。我喜欢通过使用 MVC 架构来尽可能地分散我的关注点。由于 JavaScript 是基于事件的,所以我也主要使用观察者设计模式。

这里是一个有关使用 jQuery 的 MVC 的教程。

I dont think it matters what language you use, good OOP is good OOP. I like to split up my concerns as much as possible by using an MVC architecture. Since JavaScript is very event based, I also use the observer design pattern mostly.

Heres a tutorial you can read about MVC using jQuery.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文