用Javascript编程OOP - 正确 [英] Programming OOP in Javascript - Properly

查看:90
本文介绍了用Javascript编程OOP - 正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很有兴趣将我的javascript代码改进为正确的OOP ....目前我倾向于这样做:

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) {

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

最后它只是主要是有组织的功能我认为...什么是我可以学习的好资源以OOP方式编写javascript,或者你有什么建议可以改进我目前的编程风格?

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.

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

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

推荐答案

你的问题非常广泛,所以我认为这里没有完整的答案。但这里有几点。

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. 除非你以某种方式访问​​DOM,否则你不需要包装你的代码在 jQuery(document).ready()

  2. 除非你需要从自调用匿名函数返回一个对象'关闭一些私人函数或数据

您创建的对象可以更简单地创建(好东西),就像这样

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

})();

您使用的结构,对象文字非常好,正如您所说,在分组一组函数(方法)和属性。这是一种命名空间。它也是一种创建 Singleton 的方法。您可能还想创建同一类的许多对象。

JavaScript没有类似传统OO语言的类(我会这样做)但在最简单的层面上创建一个'很容易' template'用于创建特定类型的对象。这些'模板'是称为构造函数的普通函数。

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!

关于构造函数需要了解很多。你必须四处搜寻。 SO上有很多例子。

继承是OO的基础,在js中并不直观,因为它是原型的。我不会在这里讨论,因为你很可能不会直接使用js的原生原型继承范例。

这是因为有些库可以非常有效地模仿经典继承,原型(继承) mootools(Class)那里其他人

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.

很多人说继承在OO中过度使用,你应该赞成作曲,这让我想到了当我开始这个漫无边际的答案时我最初打算推荐的内容。

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.

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

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

I建议您阅读 Pro JavaScript Design Patterns
那里,就是它

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

这篇关于用Javascript编程OOP - 正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆