函数调用的四种模式以及this的指向浅析

来源:互联网 发布:有线监控怎么连接网络 编辑:程序博客网 时间:2024/04/28 16:57

       在每个函数进行声明时会传递形式参数,除此之外函数还另外拥有两个附加的参数:arguments和this,arguments是调用时传递进来的参数组成的一个类数组的属性,同样拥有length属性即表示参数个数;而this的作用就更大了,他在面向对象的编程中非常重要,但它的值取决于函数调用模式,即方法调用模式,函数调用模式,构造器调用模式,apply调用模式。


方法调用模式

即当函数作为一个方法被调用的时,此时对象是指向调用此方法对象的。

引用the good parts的例子

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

this指向调用方法的对象


函数调用模式:

当函数不是一个我们所创建对象的属性时,无论他在什么作用域中直接以函数形式运行,此时this是绑定到window的,而解决方案是给一个变量that赋值this,内部函数就可以用他访问到this

引用the good parts的例子

myObject.double = function () {var that = this;var helper = function () {that.value = add(that.value, that.value);//这里的this是绑定到window的};helper();};myObject.double();//value === 6


this指向全局对象window


构造器调用模式

构造函数是指用对象构建语法创建函数实例,即在一个函数前面加上new初始化它,返回一个绑定this的实例对象,该对象连接到函数的prototype

引用the good parts的例子

var Quo = function (string) {this.status = string;};Quo.prototype.get_status = function () {return this.status;};var myQuo = new Quo("confused");myQuo.get_status;//confused

this指向实例


apply调用模式

首先简单介绍apply函数,它是一个作用于函数的方法,接受两个参数:被绑定给this的值和参数数组,返回值是this调用函数方法的结果

引用the good parts的例子

var array = [3,4];var sum =  add.apply(null,array);//sum === 7//创建了一个包含status的对象var statusObject = {status: "A-OK"};//apply使statusObject调用了get_statusvar status = Quo.prototype.get_status.apply(statusObject);
this的指向有apply的参数决定

1 0
原创粉丝点击