Javascript Basics Part 4

This is the fourth in a 10-part series that will introduce you to the JavaScript language.

In the last article, we covered the basics on how to work with form fields and we delved into functions a bit more. If you don't fully understand any of these concepts, you should read, or re-read the last article. 数据挖掘工具

In this article we will fully explain functions and introduce the concepts of objects in JavaScript. 数据挖掘实验室

As you already know, functions in JavaScript are used to perform the same task multiple times. Up until now, we have always called our functions manually with parenthesis: myFunction(). What if you want to run a function when the user performs a specific task? Well you can--using JavaScript--attach a function to almost any event that your user might perform. Let's see this in action by writing a function that counts how many times your user has clicked on the page.

<script type="text/javascript">

数据挖掘论坛

var clickCount = 0;
function documentClick(){
    document.getElementById('clicked').value = ++clickCount;
}
document.onclick = documentClick;

数据挖掘论坛

</script>


You have clicked on this page <input id="clicked" size="3" onfocus="this.blur();" value="0"> times.
You have clicked on this page times.

  数据挖掘交友

In previous articles we have only used the ++ operator after a variable, as in "clickCount++". In this example, however, we are using ++ before the variable. The first example, "clickCount++", adds one to clickCount after its value is read. "++clickCount", on the other hand, adds one to clickCount before its value is read. Since our clickCount variable in this example is initially set to 0, we want to add one to it before we set the value of the input box, thus we write "++clickCount".

If you look at the previous example, it should seem fairly familiar. We define a variable and a function just as we have before. What changes is that instead of calling our function, documentClick(), we are telling our code that we want the function to run every time the user clicks on the document. "document.onclick" binds the function to the document's onclick event.

  数据挖掘实验室

There are many events like "onclick". We will introduce a few of these, but a few of the most common ones are: onclick, onload, onblur, onfocus, onchange, onmouseover, onmouseout and onmousemove. You can bind a function to these events on any object, such as an image or input box, not just the document. onmouseover and onmouseout are, for example, commonly used on images to create a rollover effect.

You might have also noticed that we referenced our input box differently. We previously discussed that to reference an input box, you should use "document.forms.formName.elements.inputBoxName". While this is a good way to do this, it is not always necessary. In this example, our input box is simply acting as a counter. It is not inside of a form and we do not need it to be. So we give it an ID: id="clicked". IDs can be used to reference any object on your page. IDs must be unique on the page so if you have 5 input boxes with IDs you must give them each different IDs; even if they are only "input1"-->"input5".

Since we are using this input box as a counter, we don't want people to be able to click on it and change its value. This is where another binding, "onfocus", comes into play. "onfocus" is fired whenever the cursor is moved to the object. So if you click on the input box or if you use the tab key to get to it, "onfocus" is called.

We have a very short piece of code in our onfocus event, but it is also very important. It introduces the "this" keyword which is crucial to understand in JavaScript. "this" is a keyword that refers to whatever object the code is running on. In this example "this" is refering to our input box. In this example "this.blur()" is "blurring" our input box, in other words, forcing it to lose focus. Since this is executed as soon as the user focuses on the input box, it makes it "impossible" to change the data. 数据挖掘论坛

If "this" is used in a function, it refers to the function itself. If "this" is used in JavaScript code outside of a function, it refers to the window object. The most common uses of "this" are changing a property of the current object, as in the example above, or passing the current object to a function. 数据挖掘交友

Let's look at another example:

<script type="text/javascript">
数据挖掘交友
function showValue(obj){
    alert('You Clicked On ' + obj.value);
}
数据挖掘工具
</script>


数据挖掘实验室

<input type="radio" name="fruit" onclick="showValue(this);" value="Apple" > Apple
<input type="radio" name="fruit" onclick="showValue(this);" value="Orange" > Orange

数据挖掘工具


<input type="radio" name="fruit" onclick="showValue(this);" value="Pear" > Pear
<input type="radio" name="fruit" onclick="showValue(this);" value="Bananna"> Bananna
数据挖掘论坛

数据挖掘工具

You should notice that the onclick event for each of these radio buttons is identical. If you click each of them, however, you get different messages. This is because of the "this" keyword. Since "this" is refering to each of the individual radio buttons, we are passing each radio button to the "showValue" function seperately. 数据挖掘论坛

Getting back to functions, we need to describe how to pass arguments to a function. In the previous example, "obj" is an argument. "obj" is going to contain a reference to whatever input box you click on. You can pass as many arguments to a function as you need. If you need 10 arguments, your function could look like:

function myFunction(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10){
    // code goes here
}
In many instances, you might have a function that needs up to a certain number of arguments, but doesn't always need them all. One of the nice things about JavaScript is that you do not need to pass 10 arguments to a function that is declared to accept 10 arguments. If you only pass the first 3, the function will only have the first 3 defined. You need to take this into account when writing your functions. We might have a function that always requires the first 3 arguments, but the next 7 are optional:
function myFunction(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10){
    // do stuff with arg1
    // do stuff with arg2
    // do stuff with arg3
    if(arg4){ 数据挖掘工具
        // do stuff with arg4
    }


数据挖掘实验室

    if(arg5 && arg6 && arg7){
        // do stuff with arg5, arg6 and arg7
        if(arg8){
            // do stuff with arg8
        }
    }


数据挖掘研究院

    if(arg9 || arg10){
        // do stuff with arg9 or arg10
    }
}
You'll notice that all we are doing is saying "if(arg)". If an argument is not passed to a function you get a value of "undefined" when you try to do something with it. "undefined" is a special state in JavaScript saying that the object doesn't exist. When you try to use "undefined" as a boolean (true/false) value, as we are in our if statements, it comes back as false.

So if arg4 is not passed in our above example, it comes back as "undefined" and our if statement is not executed. 数据挖掘论坛

What if you don't know how many arguments you need? You could have a function that takes 1-->n arguments and performs an identical task on all of them. Well fortunately JavaScript gives us an "arguments" object in every function. The arguments object contains every argument in the function: 数据挖掘研究院

function myFunction(){
    for(var i=0; i<arguments.length; i++){
        alert(arguments[i].value);
    }
}
数据挖掘工具
This code will alert the value of any object(s) you pass to it. If you pass 100 objects, you will get 100 alerts. A more useful function would possibly hide/show any objects you passed to it.

One of the more interesting aspects about JavaScript is the idea that functions are objects and can be passed around like an input box, image or anything else you may have. Take a look at this code, for example: 数据挖掘工具

<script type="text/javascript">
数据挖掘实验室
function multiply(){
    var out=1;
    for(var i=0; i<arguments.length; i++){
        out *= arguments[i];
    }


数据挖掘研究院

    return out;
}


数据挖掘实验室

function add(){
    var out=0;
    for(var i=0; i<arguments.length; i++){
        out += arguments[i];
    }


数据挖掘论坛

    return out;
}


数据挖掘交友

function doAction(action){
    alert(action(1, 2, 3, 4, 5));
}
数据挖掘交友
</script>


数据挖掘实验室

<button onclick="doAction(multiply)">Test Multiply</button>
<button onclick="doAction(add)" >Test Add</button>

There is a lot going on in this little bit of code. We start off by simply defining two functions: multiply and add. Our multiply function just multiplies together any numbers you pass to it. Likewise, our add function adds together any numbers you pass to it. The magic starts with the onclick actions of our two buttons. You will notice that when you click either button you are passing an object to the doAction function. Previously, we have always passed variables or HTML objects (like our input boxes in a previous example). In this example we are passing functions. Functions can be passed the same as any other object, and when you pass them they are called the same way as any other function. The only thing that changes is their name.

数据挖掘论坛

So our doAction function takes in another function as an argument! If you pass it the multiply function it passes 1 through 5 to our multiply function and we get a value of 120. If you pass the add function to doAction the values 1 through 5 are passed to add and we get a value of 15 as a result. 数据挖掘实验室

This is actually one of the most powerful features of JavaScript and we will explore this in more detail in future articles. For now it is important that you understand the concept.

Another important feature regarding functions is the fact that you can nest them inside one another. JavaScript does not support true Object Oriented (OO) design, but this feature allows very similiar features. 数据挖掘研究院

In addition to being able to nest functions, it is important to note that there are several different ways to declare a function:

数据挖掘实验室

function myFunction(){
    function nestedFunction1(arg1, arg2, arg3){
        alert(arg1+arg2+arg3);
    }


数据挖掘论坛

    var nestedFunction2 = function(arg1, arg2, arg3){
        alert(arg1+arg2+arg3);
    }


数据挖掘研究院

    var nestedFunction3 = new Function('arg1, arg2, arg3', 'alert(arg1+arg2+arg3);');
}
数据挖掘交友
In this example, nestedFunction1, nestedFunction2 and nestedFunction3 are all identical in function. The only difference is in how they are defined. nestedFunction1 is declared like every function we have seen before this. The syntax for nestedFunction2, on the other hand, is a bit different. We are setting a variable, this.nestedFunction2, to a function. The syntax for this is "variableName = function(arguments){". Likewise for nestedFunction3, we are setting a variable to a new function. This one is drastically different, however, as we are defining our function with strings. This third example is rarely used, but is very useful when it is. It allows you to build a string containing code for a function to execute and then define the function with that string.

That's all for this primer. Our next primer will look at an area we have skipped over until now--Arrays.

数据挖掘研究院

[数据挖掘专家] [数据挖掘研究院] [数据挖掘论坛] [数据挖掘实验室]
上一篇:Javascript Basics Part 3
下一篇:用CSS制作鼠标经过图像
最新评论共有 0 位网友发表了评论 , 查看所有评论
发表评论( 不能超过250字,需审核,请自觉遵守互联网相关政策法规。 )
匿名?
数据挖掘网站导航 数据挖掘论坛导航
  • 数据挖掘工具
  • 数据挖掘论坛
  • DataCruncher - Cognos
  • MineSet - MathSoft
  • Intelligent Miner - GainSmarts
  • Sqlserver - SAS - Clementine
  • CART - Weka - WizSoft
  • NeuroShell - ModelQuest
  • data mining tools - Darwin
  • 数据挖掘交友
  • 数据挖掘博客
  • 数据挖掘工具
  • 数据挖掘资源
  • 数据挖掘技术算法
  • 数据挖掘相关期刊、会议
  • 研究院联盟合作专区
  • 数据挖掘基础与相关技术
  • 数据挖掘厂商与就业
  • 数据挖掘研究者乐园
  • 知名厂商数据挖掘工具资料
  • 国内数据挖掘实验室
  • Foreign Data Mining Lab
  • 热点关注
  • 新年矢量素材下载大集合
  • frame高度宽度固定
  • JavaScript语言参考手册_目录
  • 用XMLHTTP Post Form时的表单乱码解决方案
  • 使用Filter实现动态页面的静态HTML缓冲
  • javascript 通用库(二)
  • 用CSS制作鼠标经过图像
  • javascript 差错功能函数
  • 急死了~~checkbox传值的问题
  • javaScript基础
  • 论坛最新话题
  • Foundations of Statistical Natural Langu
  • Game Theory meet Data Mining: A Recent P
  • System Building: How does it help or hin
  • 数据挖掘与Clementine培训
  • 新手报到
  • 求 SASEM 客户流失预测分析
  • 数据挖掘工程师/搜索研究院—北京——无线
  • 数据挖掘入门介绍(如何着手数据挖掘)
  • Information Overload Survey Results
  • The INEX 2005 Workshop on Element Retrie
  • 相关资讯
  • javascript lanscape打印
  • javascript 差错功能函数
  • javascript 通用库(二)
  • javascript 通用库(一)
  • javascript 正则表达式
  • 脚本攻击防范策略完全篇
  • javaScript基础
  • 用XMLHTTP Post Form时的表单乱码解决方案
  • 中文排版CSS心得
  • 使用Filter实现动态页面的静态HTML缓冲
  • 数据挖掘实验室资料
  • 数据挖掘博客地址
  • 数据挖掘实验室网站地址
  • Prepare for Medicare audits by using dat
  • 注册成为SAS用户与爱好者俱乐部会员
  • 水南梅
  • 明日烟
  • 新人报道
  • 下载
  • 厦门服务器托管,450元/月—0592-5177319 高
  • 买空间送域名--0592-5177319 高静