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

查看:29
本文介绍了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*/}
};

那么你将使用以下方法创建一个矩形对象:

So then you would create a rectangle object by using:

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

然后你的代码永远不会干扰或被任何其他人的Rectangle干扰.

  • 使用一致的命名策略,特别是:
    • 对象名称应大写,其他所有内容(变量、函数)应以小写字符开头,即

      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 是 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();

        尝试:

        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天全站免登陆