javascript学习_函数调用模式与this取值

js的函数调用:

js的函数调用,除了声明时定义的形式参数,每个函数还接收两个附加的参数:this和arguments。而this的值取决于调用的模式。

1、方法调用模式

当一个函数被保存为一个对象的属性时,我们称它为一个方法。当一个方法被调用时,this被绑定到该对象。

例:

 1 var myObiect = {
 2     value: 0;
 3     increment: function (inc) {
 4         this.value += typeof inc === 'number' ? inc : 1;  //this指向对象
 5     }
 6 };
 7 
 8 myObject.increment();
 9 document.writeln(myObject.value);
10 
11 myObject.increment(2);
12 document.writeln(myObject.value);

方法可以使用this访问自己所属的对象,能从对象中取值并进行修改。this到对象的绑定发生在调用的时候。通过this取得所属对象的上下文的方法称为公共方法。

2、函数调用模式

当一个函数并非一个对象的属性时,那么它就是被当做一个函数来调用的。而此时this会被绑定到全局对象。导致的结果是对象的方法无法利用内部函数来帮助它工作,因为this的值不相同只能将方法的this赋值给其他变量进行引用

例:

 1 myObject.double = function () {
 2     var that = this;
 3     var helper = function () {
 4         that.value = add(that.value,that.value);
 5     };
 6     helper();
 7 };
 8 
 9 myObject.double();
10 document.writeln(myObject.value);
函数调用举例

3、构造器调用函数

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

 1 var Quo = function (string) {
 2     this.status = string;
 3 };
 4 
 5 Quo.prototype.get_status = function () {
 6     return this.status;
 7 }
 8 
 9 var myQuo = new Quo("confused");
10 
11 document.writeln(myQuo.get_status());
构造器函数举例

4、Apply调用模式

apply是函数的一个方法,apply方法让我们构建一个参数数组传递给调用函数,apply方法接收两个参数,第一个绑定给this,第二个是参数数组。

1 var array = [3,4];
2 var sum = add.apply(null,array);
3 
4 var statusObject = {
5     status: 'A-OK'; 
6 };
7 
8 var status = Quo.prototype.get_status.apply(statusObject);
原文地址:https://www.cnblogs.com/moongy/p/6409333.html