一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

js function无名函数详解

时间:2011-07-09 编辑:简简单单 来源:一聚教程网

js function无名函数详解


函数对象 Function Object

函数就是对象。对象字面量产生的对象链接到Object.prototype。函数对象链接到Function.prototype。每个函数在创建时附有两个附件的隐藏属性:函数的上下文和实现函数行为的代码。

函数字面量 Function Literal

函数对象可以通过函数字面量来创建。

var add = function(a, b){return a+b;};

调用 Invocation

除了声明时定义的形式参数,每个函数接收两个附加的参数:this 和arguments。

this在面向对象编程中非常重要,它的值取决于调用的模式。在JS中,一共有四种调用模式,这些模式在初始化参数this上存在差异。

1、方法调用模式

2、函数调用模式

3、构造器调用模式

4、apply调用模式

方法调用模式 The Mehtod Invocation Pattern

当一个函数被保存为一个对象的属性并且被调用时,this绑定到该对象。

通过this可取得他们所属对象的上下文的方法称为公共方法。

var myObject = {    value : 0,    increment:function(inc)    {           this.value += (inc);    }};myObject.increment(3);myObject.increment(3);alert(myObject.value);//result is 6.

函数调用模式 The Function Invocation Pattern

在函数调用模式下,this被绑定到全局对象上。这个是网页特效语言设计上的一个错误。

看如下code:

var g='globle';var o=function(){ var g= 'self';alert(this.g);}();//result is 'globle'. it is not correct.

可以采用以下方法避免

var g='globle';var o=function(){ var that = this;that.g='self';alert(this.g);}();//result is 'self', it is correct.

构造器调用模式 The Consultant Invocation Pattern

js是居于原型继承的语言,所以对象可以从其他对象直接继承属性。该语言是无类别的。

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

不推荐使用这种方法。

var Quo=function(string){this.status =string;};Quo.prototype.get_status = function(){return this.status;};var myQuo = new Quo("Confused");alert(myQuo.get_status());//new could not be lost.

Apply调用模式 The Apply Invocation Pattern

通过apply/call方法调用函数,其中第一个参数为我们指定的this的值。

var  statusObject = {status : 'A-OK'};var status = Quo.prototype.get_status.apply(statusObject);  //result is 'A-OK';the first param is "this" value.

热门栏目