[翻译]High Performance JavaScript(025)
第八章 Programming Practices 编程实践
Every programming language has pain points and inefficient patterns that develop over time. The appearance of these traits occurs as people migrate to the language and start pushing its boundaries. Since 2005, when the term "Ajax" emerged, web developers have pushed JavaScript and the browser further than it was ever pushed before. As a result, some very specific patterns emerged, both as best practices and as suboptimal ones. These patterns arise because of the very nature of JavaScript on the Web.
每种编程语言都有痛点,而且低效模式随着时间的推移不断发展。其原因在于,越来越多的人们开始使用这种语言,不断扩种它的边界。自2005年以来,当术语“Ajax”出现时,网页开发者对JavaScript和浏览器的推动作用远超过以往。其结果是出现了一些非常具体的模式,即有优秀的做法也有糟糕的做法。这些模式的出现,是因为网络上JavaScript的性质决定的。
Avoid Double Evaluation 避免二次评估
JavaScript, like many scripting languages, allows you to take a string containing code and execute it from within running code. There are four standard ways to accomplish this: eval(), the Function() constructor, setTimeout(), and setInterval(). Each of these functions allows you to pass in a string of JavaScript code and have it executed. Some examples:
JavaScript与许多脚本语言一样,允许你在程序中获取一个包含代码的字符串然后运行它。有四种标准方法可以实现:eval(),Function()构造器,setTimeout()和setInterval()。每个函数允许你传入一串JavaScript代码,然后运行它。例如:
var num1 = 5,
num2 = 6,
//eval() evaluating a string of code
result = eval("num1 + num2"),
//Function() evaluating strings of code
sum = new Function("arg1", "arg2", "return arg1 + arg2");
//setTimeout() evaluating a string of code
setTimeout("sum = num1 + num2", 100);
//setInterval() evaluating a string of code
setInterval("sum = num1 + num2", 100);
Whenever you're evaluating Jav
相关文档:
页面提交数据一般有两种方法:get,post。post就是所谓的form提交,使用视图;get是通过url提交。
Get方法一般用后台代码(如asp,asp.net)获得参数,代码很简单:Request.QueryString["id"];即可获取。
有些时候需要直接在前台获取url参数,要用到javascript,js没有直接获取url参数的方法,那么,我们如何通过js ......
常规的方法是将年月日取出,然后分别判断范围,然后就判断闰年2月的天数
可以通过new Date(string)的构造,比较年月日字符是否发生变化判断。
function CheckDate(text) {
if (!text) return false;
text = text.replace(/[\/-]0?/g, "/");
if (!text.match(/^\d{4}\/\d{1,2}\/\d{1,2}$/)) return true;
......
Recursion Patterns 递归模式
When you run into a call stack size limit, your first step should be to identify any instances of recursion in the code. To that end, there are two recursive patterns to be aware of. The first is the straightforward recursive pattern represented ......
Yielding with Timers 用定时器让出时间片
Despite your best efforts, there will be times when a JavaScript task cannot be completed in 100 milliseconds or less because of its complexity. In these cases, it's ideal to yield control of the UI thread so that UI updates may occur ......
Splitting Up Tasks 分解任务
What we typically think of as one task can often be broken down into a series of subtasks. If a single function is taking too long to execute, check to see whether it can be broken down into a series of smaller functions that complete in smaller ......