Javascript OOP最佳实践? [英] Javascript OOP best practices?

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

问题描述

我厌倦了在Javascript中看到几十种不同的面向对象编程方式。任何人都可以告诉我应该使用哪种技术,因为我想在大型项目上工作,我希望我的代码能够在未来证明?

I'm sick of seeing dozens of different ways of doing object oriented programming in Javascript. Can anyone just tell me which technique I should use considering I want to work on a large scale project and I want my code to be future proof?

推荐答案

这些只是我提出的一些快速指南,如果其他人有任何有意义的补充,我已将此答案设置为社区维基,因此您应该很容易编辑。

These are just a few quick guidelines I've come up with, if anyone else has anything meaningful to add, I've set this answer as a community wiki so it should be easy enough for you to edit.

  1. 命名空间您的对象,以确保它们永远不会与第三方JavaScript库冲突。

  1. Namespace your objects to ensure they will never conflict with third party JavaScript libraries.
window['Andrew']['JS'] = {
    addEvent: function(el,evName) {/*Stuff*/},
    Rectangle: function(width,height) {/*Stuff*/}
};



那么你可以使用:$ b创建一个矩形对象
$ b

So then you would create a rectangle object by using:

var myRect = new Andrew.JS.Rectangle(14,11);


然后你的代码永远不会干扰或受到干扰由任何其他人的矩形





  • 使用一致的命名策略,具体来说:

    • 对象名称应大写,其他所有内容(变量,函数)应以小写字符开头,即

      And then your code will never interfere with, or be interfered by anybody else's Rectangle.

    • Use a consistent naming strategy, specifically:
      • Object names should be capitalized, everything else (variables, functions) should begin with a lower case character i.e.

        var myRect = new Andrew.JS.Rectangle(14,11);
        document.write(myRect.getArea());



      • 确保一切都有意义,即方法,名词+形容词的动词参数。

      • myRect.getAreaObject().inSquareFeet();


        确保inSquareFeet是<$ c $返回的对象的方法c> getAreaObject()而不是的方法Andrew.JS.Rectangle

        Make sure inSquareFeet is a method of the object returned by getAreaObject() and not a method of Andrew.JS.Rectangle

        var Person = function()
        {
            this.name = "";
            this.sayHello = function ()
            {
                alert(this.name + " says 'Hello!'");
                return this;
            }
        }
        
        var bob = new Person();
        bob.name = "Bob Poulton";
        bob.sayHello();


        try:

        try:

        var Person = function(name)
        {
            this.name = name;
            this.sayHello = function ()
            {
                alert(this.name + " says 'Hello!'");
                return this;
            }
        }
        
        var bob = new Person("Bob Poulton");
        bob.sayHello();



        这篇关于Javascript OOP最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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