- 浏览: 1779239 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (641)
- vb2005xu自己动手系列 (174)
- vb2005xu开发文章转摘 (47)
- vb2005xu发发牢骚 (99)
- vb2005xu新技术灌水 (12)
- vb2005xu网络资源集锦 (21)
- vb2005xu软件学习 (60)
- 英语学习 (3)
- JavaScript 学习 (54)
- JAVA OOP 巩固 之 CustomDatabase 的开发 (5)
- 2013年9月之前所在公司 记事 (7)
- FleaPHP/QEEPHP 资料 (87)
- JAVA MAIL 学习篇 (4)
- Python turbogears (5)
- Rails 个人开发四部曲 (3)
- 名人传 (8)
- iwp framework (5)
- 高考零分作文 (5)
- startos (8)
- lua (0)
- 职场 (1)
最新评论
-
hellotieye:
自己 评论 自己 挺嗨呀
Mysql sql查询时 if 的用法 -
igevin:
转载请标明出处,转自Gevin的博客http://blog.i ...
RESTful API 编写指南 -
Theobob:
...
实现简单的ACL -
vb2005xu:
比如 对于 curl 调用就不再需要 加各种if 判断了,
$ ...
搞一个简单的数据打印工具AsDebug の Laravel -
vb2005xu:
http://geekplux.com/wiki/
YII2 模块内自定义错误页
Hey, I didn't know you could do that
If you are a web developer and come from the same place I do, you have probably used quite a bit of Javascript in your web pages, mostly as UI glue.
Until recently, I knew that Javascript had more OO capabilities than I was employing, but I did not feel like I needed to use it. As the browsers started to support a more standardized featureset of Javascript and the DOM, it became viable to write more complex and functional code to run on the client. That helped giving birth to the AJAX phenomena.
As we all start to learn what it takes to write our cool, AJAXy applications, we begin to notice that the Javascript we used to know was really just the tip of the iceberg. We now see Javascript being used beyond simple UI chores like input validation and frivolous tasks. The client code now is far more advanced and layered, much like a real desktop application or a client-server thick client. We see class libraries, object models, hierarchies, patterns, and many other things we got used to seeing only in our server side code.
In many ways we can say that suddenly the bar was put much higher than before. It takes a heck lot more proficiency to write applications for the new Web and we need to improve our Javascript skills to get there. If you try to use many of the existing javascript libraries out there, like Prototype.js , Scriptaculous , moo.fx , Behaviour , YUI , etc you'll eventually find yourself reading the JS code. Maybe because you want to learn how they do it, or because you're curious, or more often because that's the only way to figure out how to use it, since documentation does not seem to be highly regarded with most of these libraries. Whatever the case may be, you'll face some kung-fu techniques that will be foreign and scary if you haven't seen anything like that before.
The purpose of this article is precisely explaining the types of constructs that many of us are not familiar with yet.
Related article
Prototype.js documentation
JSON
JavaScript Object Notation (JSON ,) is one of the new buzzwords popping up around the AJAX theme. JSON, simply put, is a way of declaring an object in javascript. Let's see an example right away and note how simple it is.
var myPet = { color: 'black', leg_count: 4, communicate: function(repeatCount){ for(i=0;i<repeatCount;i++) alert('Woof!');} };
Let's just add little bit of formatting so it looks more like how we usually find out there:
var myPet = { color: 'black', legCount: 4, communicate: function(repeatCount){ for(i=0;i<repeatCount;i++) alert('Woof!'); } };
Here we created a reference to an object with two properties (color and legCount ) and a method (communicate .) It's not hard to figure out that the object's properties and methods are defined as a comma delimited list. Each of the members is introduced by name, followed by a colon and then the definition. In the case of the properties it is easy, just the value of the property. The methods are created by assigning an anonymous function, which we will explain better down the line. After the object is created and assigned to the variable myPet , we can use it like this:
alert('my pet is ' + myPet.color); alert('my pet has ' + myPet.legCount + ' legs'); //if you are a dog, bark three times: myPet.communicate(3);
You'll see JSON used pretty much everywhere in JS these days, as arguments to functions, as return values, as server responses (in strings,) etc.
What do you mean? A function is an object too?
This might be unusual to developers that never thought about that, but in JS a function is also an object. You can pass a function around as an argument to another function just like you can pass a string, for example. This is extensively used and very handy.
Take a look at this example. We will pass functions to another function that will use them.
var myDog = { bark: function(){ alert('Woof!'); } }; var myCat = { meow: function(){ alert('I am a lazy cat. I will not meow for you.'); } }; function annoyThePet(petFunction){ //let's see what the pet can do petFunction(); } //annoy the dog: annoyThePet(myDog.bark); //annoy the cat: annoyThePet(myCat.meow);
Note that we pass myDog.bark and myCat.meow without appending parenthesis "()" to them. If we did that we would not be passing the function, rather we would be calling the method and passing the return value, undefined in both cases here.
If you want to make my lazy cat start barking, you can easily do this:
myCat.meow = myDog.bark; myCat.meow(); //alerts 'Woof!'
Arrays, items, and object members
The following two lines in JS do the same thing.
var a = new Array(); var b = [];
As I'm sure you already know, you can access individual items in an array by using the square brackets:
var a = ['first', 'second', 'third']; var v1 = a[0]; var v2 = a[1]; var v3 = a[2];
But you are not limited to numeric indices. You can access any member of a JS object by using its name, in a string. The following example creates an empty object, and adds some members by name.
var obj = {}; //new, empty object obj['member_1'] = 'this is the member value'; obj['flag_2'] = false; obj['some_function'] = function(){ /* do something */};
The above code has identical effect as the following:
var obj = { member_1:'this is the member value', flag_2: false, some_function: function(){ /* do something */} };
In many ways, the idea of objects and associative arrays (hashes) in JS are not distinguishable. The following two lines do the same thing too.
obj.some_function(); obj['some_function']();
Enough about objects, may I have a class now?
The great power of object oriented programming languages derive from the use of classes. I don't think I would have guessed how classes are defined in JS using only my previous experience with other languages. Judge for yourself.
//defining a new class called Pet var Pet = function(petName, age){ this.name = petName; this.age = age; }; //let's create an object of the Pet class var famousDog = new Pet('Santa\'s Little Helper', 15); alert('This pet is called ' + famousDog.name);
Let's see how we add a method to our Pet class. We will be using the prototype property that all classes have. The prototype property is an object that contains all the members that any object of the class will have. Even the default JS classes, like String , Number , and Date have a prototype object that we can add methods and properties to and make any object of that class automatically gain this new member.
Pet.prototype.communicate = function(){ alert('I do not know what I should say, but my name is ' + this.name); };
That's when a library like prototype.js comes in handy. If we are using prototype.js, we can make our code look cleaner (at least in my opinion.)
var Pet = Class.create(); Pet.prototype = { //our 'constructor' initialize: function(petName, age){ this.name = petName; this.age = age; }, communicate: function(){ alert('I do not know what I should say, but my name is ' + this.name); } };
Functions as arguments, an interesting pattern
If you have never worked with languages that support closures, like Ruby or C#2.0, you may find the following idiom too funky.
var myArray = ['first', 'second', 'third']; myArray.each( function(item, index){ alert('The item in the position #' + index + ' is:' + item); });
Whoa! Let's explain what is going on here before you decide I've gone too far and navigate to a better article than this one.
First of all, in the above example we are using the prototype.js library, which adds the each function to the Array class. The each function accepts one argument that is a function object. This function, in turn, will be called once for each item in the array, passing two arguments when called, the item and the index for the current item. Let's call this function our iterator function. We could have also written the code like this.
function myIterator(item, index){ alert('The item in the position #' + index + ' is:' + item); } var myArray = ['first', 'second', 'third']; myArray.each( myIterator );
But then we would not be doing like all the cool kids in school, right? More seriously, though, this last format is simpler to understand but causes us to jump around in the code looking for the myIterator function. It's nice to have the logic of the iterator function right there in the same place it's called. Also, in this case, we will not need the iterator function anywhere else in our code, so we can transform it into an anonymous function without penalty.
Let's look at the original example again with some highlighting to hopefully make things clearer.
var myArray = ['first', 'second', 'third'];
myArray.each( function(item, index){
alert('The item in the position #' + index + ' is:' + item);
}
);
This is this but sometimes this is also that
One of the most common troubles we have with JS when we start writing our code is the use of the this keyword. It could be a real tripwire.
As we mentioned before, a function is also an object in JS, and sometimes we do not notice that we are passing a function around.
Take this code snippet as an example.
function buttonClicked(){ alert('button ' + this.id + ' was clicked'); } var myButton = document.getElementById('someButtonID'); var myButton2 = document.getElementById('someOtherButtonID'); myButton.onclick = buttonClicked; myButton2.onclick = buttonClicked;
Because the buttonClicked function is defined outside any object we may tend to think the this keyword will contain a reference to the window or document object (assuming this code is in the middle of an HTML page viewed in a browser.)
But when we run this code we see that it works as intended and displays the id of the clicked button. What happened here is that we made the onclick method of each button contain the buttonClicked object reference, replacing whatever was there before. Now whenever the button is clicked, the browser will execute something similar to the following line.
myButton.onclick();
That isn't so confusing afterall, is it? But see what happens you start having other objects to deal with and you want to act on these object upon events like the button's click.
var myHelper = { formFields: [ ], emptyAllFields: function(){ for(i=0; i<this .formFields.length; i++){ var elementID = this .formFields[i]; var field = document.getElementById(elementID); field.value = ''; } } }; //tell which form fields we want to work with myHelper.formFields.push('txtName'); myHelper.formFields.push('txtEmail'); myHelper.formFields.push('txtAddress'); //clearing the text boxes: myHelper.emptyAllFields(); var clearButton = document.getElementById('btnClear'); clearButton.onclick = myHelper.emptyAllFields;
So you think, nice, now I can click the Clear button on my page and those three text boxes will be emptied. Then you try clicking the button only to get a runtime error. The error will be related to (guess what?) the this keyword. The problem is that this.formFields is not defined if this contains a reference to the button, which is precisely what's happening. One quick solution would be to rewrite our last line of code.
clearButton.onclick = function(){ myHelper.emptyAllFields(); };
That way we create a brand new function that calls our helper method within the helper object's context.
发表评论
-
常用的 js 代码梳理
2016-06-16 12:00 1926/** * 格式化时间函数 * @param {form ... -
fineuploader 跨子域上传文件 cookie丢失问题的解决
2015-10-14 13:30 4814目前的项目中,使用到了fineuploader 这个纯htm ... -
2014 I Love You!
2014-02-14 15:40 1273保存成 html文件后打开 写道 <html> ... -
阻止checkbox的父元素事件冒泡
2014-01-15 20:33 8743今天在开发后台权限管理时使用了tinyaccordion ... -
整理下之前的js代码 moogens.js 记录下
2013-11-26 11:49 1212moogens.jshttps://github.com/v ... -
AOP 在js中的应用
2013-08-29 19:21 0http://www.alloyteam.com/2013/ ... -
自己动手增强 jquery.multiselect2side 调用
2012-11-13 17:50 8636最近用到一个jq插件 jquery.multiselect ... -
坑爹的HTML5应用集锦
2012-11-06 16:23 12521. 3D的俄罗斯方块 http://alteredquali ... -
小旭改的分页代码
2012-10-22 15:54 1350/** * 说明: 在页面指定元素中构建分页条 * ... -
一道js题 的分析历程
2012-08-10 11:14 1317var a = {n:1};a.x=a={n:2}; a.x ... -
修复 artDialog 双击遮罩层就会自动关闭的bug.... 自己动手....
2012-05-24 21:21 6091今天使用的时候发现 双击遮罩层 就会自动关闭 ,我用的版本是 ... -
jquery 也不给力啊 unbind 你让我情何以堪!
2012-05-09 19:36 1529发现一个问题$a = jQuery('img[src=&q ... -
使用 nodejs 形式的语法来规整 js
2012-04-21 10:20 1995/* * 使用 nodejs 形式的语法来规整 js ... -
注册了2个域名 希望能给nodejs一点集合
2011-06-22 12:37 1333NODEJS-OPEN.COM NODEJS-OPEN.I ... -
css 文本折行
2011-05-12 10:27 8377word-wrap:break-word; overflow: ... -
IE 中document.getElementsByName
2011-05-06 10:40 2452IE 中使用 document.getElementsByNa ... -
新年里 把 自己写的 js基础代码 做个了结..... 死机了吧,悲剧了吧 ... 打不开了吧...编辑器bug出现了吧 ff不能黏贴,复制,换组织就不修正么?
2011-02-11 20:28 1778新年里 把 自己写的 js基础代码 做个了结..... 死机了 ... -
考考你们的JS 我只作对了一半 你们试试
2011-02-11 10:40 2181alert(typeof(NaN)); alert( ... -
为自己的JS库 moogens 增加 facebox 组件
2011-01-17 20:16 2089之前的JS慢慢积累下来慢慢也就自己完善了个,比之前的__ini ... -
Kenxu Events.js 使用
2010-10-19 18:38 1645之前写过 iamseseJS和__xu_init jS简易框架 ...
相关推荐
"JavaScript高级程序设计" 是一个深入探讨此语言精髓的教程,由国外知名专家编写,以其详尽的内容和深入的讲解闻名。这份PDF教程旨在帮助开发者提升对JavaScript的理解,掌握其高级特性和实践技巧。 首先,我们来...
最后,视频教程可能会涵盖一些实际项目开发的例子,让你有机会将所学知识付诸实践,比如开发一个简单的桌面应用程序或者移动应用。 通过《C++ Qt编程视频教程》,你不仅可以掌握Qt的基本用法,还能深入了解其高级...
书中提到的Django是一个高级的Python Web框架,它鼓励快速开发和干净、实用的设计。Django的“Pythonic”理念意味着它鼓励编写出符合Python风格的代码,即简洁、明确、优雅。Web开发不仅仅是用Python编写,还要体现...
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,它让开发者能够在服务器端使用 JavaScript 编程,打破了 JavaScript 原本只能在浏览器端运行的限制。本教程将详细介绍如何安装 Node.js v16.20.2 稳定版...
2. **theserverside.com**:这是一个专注于服务器端开发的网站,涵盖了Java、.NET、Python等多种技术领域的最新资讯、深度文章和实用教程。特别对于Java开发者而言,这里是一个获取行业动态、技术趋势和最佳实践的...
jQuery是一个高效、简洁且功能丰富的JavaScript库,它极大地简化了JavaScript编程,特别是DOM操作、事件处理、动画制作以及AJAX交互等方面的工作。 ### jQuery简介 jQuery是由John Resig在2006年创建的,它的核心...
- **constructor属性**:所有构造函数实例都有一个constructor属性,它指向其构造函数。 - **类型检查运算符**:介绍JavaScript中如何使用类型检查运算符来判断基本值和复杂值。 #### 代码示例与教学方法 - **少言...
Next.js 是一个由 Vercel 公司维护的开源库,它为 React 应用程序提供了服务器端渲染(SSR)和静态站点生成(SSG)的能力,使得开发者能够更轻松地构建全栈Web应用。这个名为 "react-AwesomeNextjs关于Nextjs使用的...
"海外游戏源码 游戏平台源码 手机游戏源码.zip"这个压缩包可能包含了一系列用于构建游戏及其平台的源代码,这对于游戏开发者、学生以及对游戏编程感兴趣的人来说,是一个宝贵的学习资源。 首先,我们要理解游戏源码...
高级java笔试题 资源教程: 综合类 入门类 效果类 工具类 慕课专题 周报类 ###六. API: ####1. 总目录 开发中心 综合Bug集合网站 综合搜索 综合API 英文综合API网站 ####2. jQuery ####3. Ecmascript ####4. Js ...
动态表头是ExtJS中一个高级特性,它允许开发者根据需要在运行时动态地创建和修改表格的列结构。这在处理数据展示和操作时具有很大的灵活性,尤其在数据字段不确定或需要自定义的情况下非常实用。 标题“extjs 实现...
高级java笔试题 五. 资源教程: 综合类 入门类 效果类 工具类 慕课专题 周刊类 六. API: 1. 总目录 开发中心 综合Bug集合网站 综合搜索 综合API 英文综合API网站 中文综合API网站 英文综合API网站 2. jQuery 3. ...
总的来说,dhtmlxTree是一个功能强大的JavaScript库,对于需要在Web应用中展示和管理层次数据的开发者来说,是一个理想的选择。结合其良好的文档和广泛的社区支持,使得它成为国外公认的最好js树框架之一。通过灵活...
根据前面的推测,这很可能是统计分析的专业资源,可能包含代码示例、教程、案例研究,甚至是一个统计分析软件的离线版。 综合以上信息,这个压缩包很可能是一个综合性的统计分析学习资料包,涵盖了理论知识、实践...
4. **jQuery and CSS Example: Create the Fanciest Drop Down Menu You Ever Saw**:教程教你如何利用jQuery和CSS构建一个引人注目的高级下拉菜单。 5. **A Different Top Navigation**:为顶部导航栏提供创新设计...
本教程将详细讲解如何利用C#中的`webBrowser1`控件来创建一个简单的浏览器程序,名为"MyIE",这个程序能够加载网页,执行基本的浏览操作。 首先,我们需要理解`webBrowser1`控件是什么。这是.NET Framework提供的一...