编写可维护面向对象的JavaScript代码[翻译]

Writing maintainable Object-Oriented (OO) JavaScript will save you money and make you popular. Don't believe me? Odds are that either you or someone else will come back and work with your code. Making that as painless an experience as possible will save time, which we all know equates to money. It will also win you the favor of those for whom you just saved a headache. But before we dive into writing maintainable OO JavaScript, let's just take a quick look at what OO is all about. If you know already about OO, feel free to skip the next section.

What is OO?
Object-oriented programming basically represents physical, real-world objects that you want to work with in code. In order to create objects, you need to first define them by writing what's called a class. Classes can represent pretty much anything: accounts, employees, navigation menus, vehicles, plants, advertisements, drinks, etc... Then, every time you want to create an object to work with, you instantiate one from a class. In other words, you create an instance of a class which gives you an object to work with. In fact, the best time to be using objects is when you'll be dealing with more than one of anything. Otherwise, a simple functional program will likely do just as well. Objects are essentially containers for data. So in the case of an employee object, you might store their employee number, name, start date, title, salary, seniority, etc... Objects also include functions (called methods) to handle that data. Methods are used as intermediaries to ensure data integrity. They're also used to transform data before storing it. For example, a method could receive a date in an arbitrary format then convert it to a standardized format before storing it. Finally, classes can also inherit from other classes. Inheritance allows you to reuse code across different types of classes. For example, both bank account and video store account classes could inherit from a base account class which would provide fields for profile information, account creation date, branch information, etc... Then, each would define its own transactions or rentals handling data structures and methods.

Warning: JavaScript OO is different
In the previous section I outlined the basics of classical object-oriented programming. I say classical because JavaScript doesn't quite follow those rules. Instead, JavaScript classes are actually written as functions and inheritance is prototypal. Prototypal inheritance basically means that rather than classes inheriting from classes, they inherit from objects using the prototype property.

Object Instantiation
Here's an example of object instantiation in JavaScript:

代码如下:

// Define the Employee class
function Employee(num, fname, lname) {
this.getFullName = function () {
return fname + " " + lname;
}
};
// Instantiate an Employee object
var john = new Employee("4815162342", "John", "Doe");
alert("The employee's full name is " + john.getFullName());

There are three important things to note here:

I uppercased the first letter of my "class" function. That important distinction lets people know that it's for instantiation and not to be called as a normal function.
I use the new operator when instantiating. Leaving it out would simply call the function and result in problems.
Though getFullName is publicly available because it's assigned to the this operator, fname and lname are not. The closure created by the Employee function gives getFullName access to fname and lname while allowing them to remain private from everyone else.
Prototypal Inheritance
Now, here's an example of prototypal inheritance in JavaScript:

代码如下:

// Define Human class
function Human() {
this.setName = function (fname, lname) {
this.fname = fname;
this.lname = lname;
}
this.getFullName = function () {
return this.fname + " " + this.lname;

}
}

// Define the Employee class
function Employee(num) {
this.getNum = function () {
return num;
}
};
// Let Employee inherit from Human
Employee.prototype = new Human();

// Instantiate an Employee object
var john = new Employee("4815162342");
john.setName("John", "Doe");
alert(john.getFullName() + "'s employee number is " + john.getNum());

This time, I've created a Human class which contains properties common to humans--I moved fname and lname there since all humans, not just employees have names. I then extended the Employee class by assigning a Human object to its prototype property.

Code Reuse Through Inheritance
In the previous example, I split the original Employee class in two. I moved out all the properties common to all humans into a Human class, and then caused Employee to inherit from Human. That way, the properties laid out in Human could be used by other objects such as Student, Client, Citizen, Visitor, etc... As you may have noticed by now, this is a great way to compartmentalize and reuse code. Rather than recreating all of those properties for every single type of object where we're dealing with a human being, we can just use what's already available by inheriting from Human. What's more, if we ever wanted to add a property like say, middle name, we'd do it once and it would immediately be available to everyone inheriting from Human. Conversely, if we only wanted to add a middle name property to just one object, we could do it directly in that object instead of adding it to Human.

Public and Private
I'd like to touch on the subject of public and private variables in classes. Depending on what you're doing with the data in an object, you'll want to either make it private or public. A private property doesn't necessarily mean that people won't have access to it. You may just want them to go through one of your methods first.

Read-only
Sometimes, you only want a value defined once at the moment the object is created. Once created, you don't want anyone changing that value. In order to do this, you create a private variable and have its value set on instantiation.

代码如下:

function Animal(type) {
var data = [];
data['type'] = type;
this.getType = function () {
return data['type'];
}
}

var fluffy = new Animal('dog');
fluffy.getType(); // returns 'dog'

In this example, I create a local array called data within the Animal class. When an Animal object is instantiated, a value for type is passed and set in the data array. This value can't be overwritten as it's private (the Animal function defines its scope). The only way to read the type value once an object is instantiated is to call the getType method that I've explicitly exposed. Since getType is defined inside Animal, it has access to data by virtue of the closure created by Animal. This way, people can read the object's type but not change it.

It's important to note that the "read-only" technique will not work when an object is inherited from. Every object instantiated after the inheritance is performed will share those read-only variables and overwrite each other's values. The simplest solution is to convert the read-only variables in the class to public ones. If however, you must keep them private, you can employ the technique pointed out by Philippe in the comments.

Public
There are times however, that you'll want to be able to read and write a property's value at will. To do that, you need to expose the property using the this operator.

代码如下:

function Animal() {
this.mood = '';
}

var fluffy = new Animal();
fluffy.mood = 'happy';
fluffy.mood; // returns 'happy'

This time our Animal class exposes a property named mood which can be written to and read at will. You can equally assign a function to public properties like the getType function in the previous example. Just be careful not to assign a value to a property like getType or you'll destroy it with your value.

Completely Private
Finally, you might find yourself in scenarios where you need a local variable that's completely private. In this case, you can use the same pattern as the first example and just not create a public method for people to access it.

代码如下:

function Animal() {
var secret = "You'll never know!"
}
var fluffy = new Animal();

Writing a Flexible API
Now that we've covered class creation, we need to future proof them in order to keep up with product requirement changes. If you've done any project work, or maintained a product long-term, you know that requirements change. It's a fact of life. To think otherwise is to doom your code to obsolescence before it's even written. You may suddenly have to animate your tab content, or have it fetch data via an Ajax call. Though it's impossible to truly predict the future, it is possible to write code that's flexible enough to be reasonably future proof.

Saner Parameter Lists
One place where future-proofing can be done is when designing parameter lists. They're the main point of contact for people implementing your code and can be problematic if not well designed. What you want to avoid are parameter lists like this:

代码如下:

function Person(employeeId, fname, lname, tel, fax, email, email2, dob) {
};

This class is very fragile. If you want to add a middle name parameter once you've released the code, you're going to have to do it at the very end of the list since order matters. That makes it awkward to work with. It also makes it difficult to work with if you don't have values for each parameter. For example:

代码如下:

var ara = new Person(1234, "Ara", "Pehlivanian", "514-555-1234", null, null, null, "1976-05-17");

A cleaner, more flexible way of approaching parameter lists is to use this pattern:

代码如下:

function Person(employeeId, data) {
};

The first parameter is there because it's required. The rest is lumped together in an object which can be very flexible to work with.

代码如下:

var ara = new Person(1234, {
fname: "Ara",
lname: "Pehlivanian",
tel: "514-555-1234",
dob: "1976-05-17"
});

The beauty of this pattern is that it's both easy to read and highly flexible. Note how fax, email and email2 were completely left out. Also, since objects aren't order specific, adding a middle name parameter is as easy as throwing it in wherever it's convenient:

代码如下:

var ara = new Person(1234, {
fname: "Ara",
mname: "Chris",
lname: "Pehlivanian",
tel: "514-555-1234",
dob: "1976-05-17"
});

The code inside the class doesn't care because the values get accessed by index like so:

代码如下:

function Person(employeeId, data) {
this.fname = data['fname'];
};

If data['fname'] returns a value, it gets set. Otherwise, it doesn't, and nothing breaks.

Make It Pluggable
As time goes on, product requirements might demand additional behavior from your classes. Yet often times that behavior has absolutely nothing to do with your class's core functionality. It's also likely that it's a requirement for only one implementation of the class, like fading in the contents of one tab's panel while fetching external data for another. You may be tempted to put those abilities inside your class, but they don't belong there. A tab strip's responsibility is to manage tabs. Animation and data fetching are two completely separate things and should be kept outside the tab strip's code. The only way to future proof your tab strip and keep all that extra functionality external, is to allow people to plug behaviors into your code. In other words, allow people to hook into key moments in your code by creating events like onTabChange, afterTabChange, onShowPanel, afterShowPanel and so on. That way, they can easily hook into your onShowPanel event, write a handler that fades in the contents of that panel and everyone is happy. JavaScript libraries allow you to do this easily enough, but it's not too hard to work it out on your own. Here's a simple example using YUI 3.

代码如下:

<script type="text/javascript" src="http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js"></script>
<script type="text/javascript">
YUI().use('event', function (Y) {

function TabStrip() {
this.showPanel = function () {
this.fire('onShowPanel');

// Code to show the panel
this.fire('afterShowPanel');
};
};

// Give TabStrip the ability to fire custom events
Y.augment(TabStrip, Y.EventTarget);
var ts = new TabStrip();

// Set up custom event handlers for this instance of TabStrip
ts.on('onShowPanel', function () {
//Do something before showing panel
});
ts.on('onShowPanel', function () {
//Do something else before showing panel
});
ts.on('afterShowPanel', function () {
//Do something after showing panel
});

ts.showPanel();
});
</script>

This example has a simple TabStrip class with a showPanel method. The method fires two events, onShowPanel and afterShowPanel. It's given the ability to do so by augmenting the class with Y.EventTarget. Once that's done, we instantiate a TabStrip object and assign a bunch of event handlers to it. This is our custom code for handling this instance's unique behavior without messing with the actual class.

Summary
If you plan on reusing code either on the same page, website or across multiple projects, consider packaging and organizing it in classes. Object-oriented JavaScript lends itself naturally to better code organization and reuse. What's more, with a little forethought, you can make sure that your code is flexible enough to stay in use long after you've written it. Writing reusable, future-proof JavaScript will save you, your team and your company time and money. That's sure to make you popular.

这本书比较适合有一定javascipt代码基础,但是需要提高代码规范性的开发人员看

个人的收获:

1.书写代码 的规范性

@书写要合理缩进

@行太长时,要记得换行,并注意下一行缩进

@空行,对每一个逻辑分支,以模块进行注释

@变量的命名以驼峰形式,统一 规范命名

@===与==的用法要注意,能用===时一定不要用==,异步的我们要与开发确认好数据的类型

@双括号要有适当空格,提高阅读性

@ switch case要用缩进一下,并用break结束

2.css与html,js分离

在html里最好不要内联,要使用外联形式,display内联是可以使用的

标签里不要内联事件,做好JS事件和标签分离

在脚本里面用css,最好用classname.不要直接写一些样式。做好css和js的分离

3.try catch

捕获错误,好处可以看到哪个地方出现了问题,能及时发现,减少调试的时间,要充分利用组件中的报错机制

4.配置文件config的新建和分离

配置一些常量及值,或者是一些message文本信息

(0)

相关推荐

  • 如何编写高质量JS代码(续)

    继续上一篇文章<如何编写高质量JS代码>今次整理一下javascript函数知识点. 2.使用函数 函数给程序员提供了主要的抽象功能,又提供实现机制.函数可以独立实现其他语言中的多个不同的特性,例如,过程.方法.构造函数,甚至类或模块. 2.1 理解函数调用.方法调用以及构造函数调用之间的不同 针对面向对象编程,函数.方法和类的构造函数是三种不同的概念. 使用模式: 1,函数调用 复制代码 代码如下: function hello(username){     return "hel

  • 在iframe里的页面编写js,实现在父窗口上创建动画效果展开和收缩的div(不变动iframe父窗口代码)

    复制代码 代码如下: <%@ page contentType="text/html; charset=GBK" language="java"%> <%@ page import="com.jstrd.mm.business.sysmgr.monitor.logic.MMStock2BudgetLogic" %> <% String query = request.getParameter("query&

  • 编写跨浏览器的javascript代码必备[js多浏览器兼容写法]

    序号 操作 分类 IE(6.0) FireFox(2.0) Mozilla(1.5) 当前浏览器 备注 1 "." 访问tag的固有属性 OK OK OK OK 2 "." 访问tag的用户定义属性eg: <input type="checkbox" myattr="test"> OK NO NO OK 可以用getAttribute函数 替代 3 obj.getAttribute 访问tag的固有属性 OK OK

  • 最佳JS代码编写的14条技巧

    写任何编程代码,不同的开发者都会有不同的见解.但参考一下总是好的,下面是来自Javascript Toolbox发布的14条最佳JS代码编写技巧. 1. 总是使用 var 在javascript中,变量不是全局范围的就是函数范围的,使用var关键词将是保持变量简洁明了的关键.当声明一个或者是全局或者是函数级(function-level)的变量,需总是前置var关键词,下面的例子将强调不这样做潜在的问题. 不使用 Var 造成的问题 var i=0; // This is good - crea

  • 如何编写高质量JS代码

    想写出高效的javascript类库却无从下手: 尝试阅读别人的类库,却理解得似懂给懂: 打算好好钻研js高级函数,但权威书上的内容太零散, 即使记住"用法",但到要"用"的时候却没有想"法". 也许你和我一样,好像有一顾无形的力量约束着我们的计划,让我们一再认为知识面的局限性,致使我们原地踏步,难以向前跨越. 这段时间,各种作业.课程设计.实验报告,压力倍增.难得挤出一点点时间,绝不睡懒觉,整理总结往日所看的书,只为了可以离写自己的类库近一点.

  • 编写高质量JavaScript代码的基本要点

    才华横溢的Stoyan Stefanov,在他写的由O'Reilly初版的新书<JavaScript Patterns>(JavaScript模式)中,我想要是为我们的读者贡献其摘要,那会是件很美妙的事情.具体一点就是编写高质量JavaScript的一些要素,例如避免全局变量,使用单变量声明,在循环中预缓存length(长度),遵循代码阅读,以及更多. 此摘要也包括一些与代码不太相关的习惯,但对整体代码的创建息息相关,包括撰写API文档.执行同行评审以及运行JSLint.这些习惯和最佳做法可以

  • 深入理解javascript学习笔记(一) 编写高质量代码

    一.变量 •全局变量 JavaScript的两个特征,不自觉地创建出全局变量是出乎意料的容易.首先,你可以甚至不需要声明就可以使用变量:第二,JavaScript有隐含的全局概念,意味着你不声明的任何变量都会成为一个全局对象属性(不是真正意义上的全局变量,可以用delete删除) 复制代码 代码如下: function sum(x,y) { // result 未声明,为隐式全局变量 result = x + y; return result; } function foo() { // 使用任

  • 深入理解JavaScript系列(1) 编写高质量JavaScript代码的基本要点

    具体一点就是编写高质量JavaScript的一些要素,例如避免全局变量,使用单变量声明,在循环中预缓存length(长度),遵循代码阅读,以及更多. 此摘要也包括一些与代码不太相关的习惯,但对整体代码的创建息息相关,包括撰写API文档.执行同行评审以及运行JSLint.这些习惯和最佳做法可以帮助你写出更好的,更易于理解和维护的代码,这些代码在几个月或是几年之后再回过头看看也是会觉得很自豪的. 书写可维护的代码(Writing Maintainable Code ) 软件bug的修复是昂贵的,并且

  • 编写Js代码要注意的几条规则

    1.不要大量使用document.write() 2.检查客户端支持对象的能力(渐进式)而不是检查其客户端,测试要使用的对象. 3.访问既有HTML中的内容而不是通过Js添加HTML(行为层与结构层分离) 4.不要使用专有DOM对象(例如IE的document.all) 5.将脚本放进一个.js文件而不是在HTML中到处可见. 6.对运行良好而且不用客户端编程的网站进行改进,而不是首先添加脚本然后添加非脚本的备用方案. 7.代码要保持独立,不要使用可能与其他脚本冲突的全局变量.(可用对象字面量)

  • 编写可维护面向对象的JavaScript代码[翻译]

    Writing maintainable Object-Oriented (OO) JavaScript will save you money and make you popular. Don't believe me? Odds are that either you or someone else will come back and work with your code. Making that as painless an experience as possible will s

  • 如何编写高质量 JavaScript 代码

    目录 一.易阅读的代码 1.统一代码格式 2.去除魔术数字 3.单一功能原则 二.高性能的代码 1.优化算法 2.使用内置方法 3.减少作用域链查找 4.避免做重复的代码 三.健壮性的代码 1.使用新语法 2.随时可扩展 3.避免副作用 4.整合逻辑关注点 前段时间有一个叫做"人类高质量男性"的视频火了,相信很多同学都刷到过.所以今天给大家分享下,什么叫做"人类高质量代码",哈哈,开个玩笑. 其实分享的都是一些自己平时总结的小技巧,算是抛砖引玉吧,希望能给大家带来一

  • 【经验总结】编写JavaScript代码时应遵循的14条规律

    本文讲述了编写JavaScript代码时应遵循的14条规律.分享给大家供大家参考,具体如下: 1. 总是使用 'var' 在javascript中,变量不是全局范围的就是函数范围的,使用"var"关键词将是保持变量简洁明了的关键.当声明一个或者是全局或者是函数级(function-level)的变量,需总是前置"var"关键词,下面的例子将强调不这样做潜在的问题. 不使用 Var 造成的问题 var i=0; // This is good - creates a

  • JAVASCRIPT代码编写俄罗斯方块网页版

    俄罗斯方块方块是小时候的一个回忆,从最开始的掌上的黑白游戏机,到电视游戏机,到电脑,无不有它的痕迹,今天我们来一起重温它的一种实现方法,也算是整理一下我的思路吧...... HTML+CSS+JS实现俄罗斯方块完整版,素材只有图片,想要的下载图片按提示名字保存,css中用的时候注意路径!!主要在JS中!JS附有详细注释 效果: 按键提示:[键盘按键] 素材:图片名字与代码里对应 1.背景图片:tetris.png 2.失败时候的弹出框图片:game-over.png 3.七种色彩小方块图片:  

  • 如何利用Promises编写更优雅的JavaScript代码

    你可能已经无意中听说过 Promises,很多人都在讨论它,使用它,但你不知道为什么它们如此特别.难道你不能使用回调么?有什么了特别的?在本文中,我们一起来看看 Promises 是什么以及如何使用它们写出更优雅的 JavaScript 代码. Promises 易于阅读 比如说我们想从 HipsterJesus 的API中抓取一些数据并将这些数据添加到我们的页面中.这些 API 的响应数据形式如下: { "text": "<p>Lorem ipsum...<

  • 编写高性能Javascript代码的N条建议

    多年来,Javascript一直在web应用开发中占据重要的地位,但是很多开发者往往忽视一些性能方面的知识,特别是随着计算机硬件的不断升级,开发者越发觉得Javascript性能优化的好不好对网页的执行效率影响不明显.但在某些情况下,不优化的Javascript代码必然会影响用户的体验.因此,即使在当前硬件性能已经大大提升的时代,在编写Javascript代码时,若能遵循Javascript规范和注意一些性能方面的知识,对于提升代码的可维护性和优化性能将大有好处. 下面给出编写高性能的Javas

  • 使用CoffeeScrip优美方式编写javascript代码

    JavaScript无疑是在web最伟大的发明之一,几乎一切网页动态效果都是基于它丰富的计算能力.而且它的能力在各种新的JavaScript的Engine下也越来越强了,比如Google Chrome用的V8 Engine. 但是由于诞生的太早,有很多语法定义在今天看来有些效率低下了,一些更加先进的语法形式,由于历史原因,没办法加入到现在的JavaScript语言中,可以说一种遗憾. 世界上的很多天才都在为构建更好的JavaScript而努力.已经有了很多尝试,其中最有前途的,无非就是Coffe

  • C++ 17标准正式发布! 更简单地编写和维护代码

    C++17 是继 C++14 之后,C++ 编程语言 ISO/IEC 标准的下一次修订的非正式名称.而就在昨日,ISO C++ 委员会正式发布了 C++ 17 标准,官方名称为 ISO/IEC 14882:2017. C++ 17 标准化图表 C ++ 17 主要特性 基于 C++ 11,C++ 17 旨在使 C++ 成为一个不那么臃肿复杂的编程语言,以简化该语言的日常使用,使开发者可以更简单地编写和维护代码. C++ 17 是对 C++ 语言的重大更新,引入了许多新的语言特性: UTF-8 字

随机推荐