Funtions in JavaScript

来源:互联网 发布:威少上赛季每场数据 编辑:程序博客网 时间:2024/06/03 03:42

1. 调用 invocation

除了声明时定义的形式参数吗,每个函数接收两个附加的参数:this and arguments。参数 this 在面向对象编程中非常重要,this 的值取决于JavaScript的调用模式(共四种):


方法调用模式  the method invocation pattern


var myObject = {value: 0,increment: function (inc){this.value += typeof inc === 'number' ? inc : 1;}};myObject.increment();document.writeln(myObject.value); // 1myObject.increment(2);document.writeln(myObject.value); //3

方法可以用this去访问对象,所以它能从对象中取值或修改该对象。this 到对象的绑定发生在调用的时候。


函数调用模式 the function invocation pattern  

当一个函数并非一个对象的属性时,那么它被当做一个函数来调用: 当函数以此模式调用时,this 被绑定到全局对象。方法不能利用内部函数来帮助它工作,因为内部函数的 this 被绑定了错误的值,所以不能共享该方法对对象的访问权。

有一解决方案,如果该方法定义一个变量并给它赋值为 this ,那么内部函数就可以通过这个变量访问到 this ,按照约定, 给次变量命名为 that :

var sum = add(3, 4);myObject.double = function() { //给 myObject 增加一个 double 方法var that = this;//  解决方法var helper = function() {that.value = add(that.value, that.value);};helper(); //以方法的形式调用 helper()};myObject.double();  <span style="font-family: Arial, Helvetica, sans-serif;">// 以方法的形式调用 double</span>document.writeln(myObject.getValue()); // 6



构造器调用模式 the constructor invocation pattern (并不推荐使用)

如果在一个函数前面带上 new 来调用, 那么将创建一个隐藏连接到该函数的 prototype 成员的新对象, 同事 this 将会被绑定到那个新对象上。

new 前缀也会该变 return 语句的行为。

//创建一个名为 Quo 的构造器函数。它构造一个带有status属性的对象var Quo = function (string){this.status = string;};//给所有的QUO实例提供一个名为 get_status 的公共方法Quo.prototype.get_status = function() {return this.status;};//构造一个 Quo 实例var myQuo = new Quo("confused");document.writeln(myQuo.get_status());  // confused


apply调用模式 the apply invocation pattern

<strong>var array = [3, 4];var sum = add.apply(null, array);  //sum == 7</strong>//构造一个包含 status 成员的对象<strong>var statusObject = {status: 'A-OK'};var status = Quo.prototype.get_status.apply(statusObject); // status 为 'A-OK'</strong>


2. 返回 Return 

一个函数总是会返回一个值。如果没有指定返回值, 则返回 undefined

如果函数以在前面加上 new 的方式来调用,则返回值不是一个对象,则返回 this (该新对象)。


3. 异常 Exceptions

Javascript 提供了一套异常处理机制。

var add = function  (a, b) {if (typeof a !== 'number' || typeof b !== 'number'){throw {name: 'TypeError',message: 'add needs numbers'};}return a + b;}
抛出 exception 对象,并被接收

var try_it = function(){try {add("seven");}catch(e) {document.writeln(e.name + ': ' + e.message);}}Try_It();


4. 递归 Recursion

递归函数可以非常高效地操作树形结构,比如浏览器端的文档对象模型(DOM)。每次递归处理给定树的一小段。

//顺序访问树每个节点var walk_the_DOM = function walk(node, func){func(node);node = node.firstChild;while(node){walk(node, func);node = node.nextSibling;}};//取得一个属性名称字符串和一个可选的匹配值。匹配的节点会被保存到一个结果数组中var getElementsByAttribute = function(node){var results = [];walk_the_DOM(document.body, function (node){var actual = node.nodeType === 1 && node.getAttribute(att);if (typeof actual === 'string' && (actual === value || typeof value !== 'string')){results.push(node);    }});return results;};



5. 闭包 Closure

In JavaScript, if you use the functionkeyword inside another function, you are creating a closure.

Two one sentence summaries:

  • a closure is the local variables for a function — kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-frame' were malloc'ed instead of being on the stack!).

The following code returns a reference to a function:

function sayHello2(name) {    var text = 'Hello ' + name; // Local variable    var sayAlert = function() { alert(text); }    return sayAlert;}var say2 = sayHello2('Bob');say2(); // alerts "Hello Bob"






0 0
原创粉丝点击