函数的四种调用模式

函数的四种调用模式

  • 普通函数执行 this=>window (声明一个函数后就直接调用)
1
2
3
4
5
function foo(){
console.log(1);
console.log(this === window);
}
foo();
  • 方法调用 this=>该方法的调用者 (通过一个对象来调用方法)
1
2
3
4
5
6
7
var obj = {
sayHi: function(){
console.log('hello,ksir.');
console.log(this === obj);
}
};
obj.sayHi();
  • 构造函数模式 this=>当前要创建出来的实例(对象) (配合new操作符来调用函数)
1
2
3
4
5
function fn(name){
this.name = name;
console.log(this);
}
var ksir = new fn('ksir');
  • call/apply模式(上下文模式)

    • this=>使用动态指定的 (指定call 或者 apply 方法的第一个参数)
    • 区别:
    • call 的参数大于等于2 , 第一个以后的为实参列表
    • apply 的参数只有两个,第二个是实参数组

    • 注意:在非严格模式下,如果thisObj 赋值为null或者不传实参,此时this->window对象,就相当于普通函数执行模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//只有函数对象才有call和apply方法
//<fn>.call()
//动态指定某方法或函数执行时内部this指向
//A:<fn>.call(thisObj,arg1,arg2,...argN)
//thisObj: 是fn在执行时this指向
//arg1,arg2,...,argN: 是fn在执行时传入的实参列表


function fn(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
console.log(this);
}
var ksir = new fn('ksir');
var o = {};
fn.call(o,'o',18,'man');
console.log(o.name);
console.log(Function.prototype);
1
2
3
4
5
6
7
8
9
10
11
//B:<fn>.apply(thisObj,[fn实参])
function foo(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
var ksir = {};
foo.apply(ksir,['ksir',21,'男']);
console.log(ksir.name);
console.log(ksir.age);
console.log(ksir.gender);

上下文模式的应用

  • 数组合并
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var arr1 = [1,2,3];
var arr2 = [4,5,6];
//数组合并,将arr2上的元素合并到arr1中
//方法一
for(var i,l = arr2.length; i<l;i++){
arr1.push(arr2[i]);
}
console.log(arr1);

//方法二
var new arr = arr1.concat(arr2);

//方法三
arr1.push.apply(arr1,arr2);
//[].push.apply(arr1,arr2);
//
Array.prototype.push.apply(arr1,arr2);
console.log(arr1);
console.log(arr1);
  • 借调方法(函数)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function parent(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}

function child(name,age,gender,address){
//对象冒充方法
//this.parent = parent;
//this.parent(name,age,gender);
//this.address = address;
//delete this.parent;

parent.call(this,name,age,gender);
this.address = address;
}d

var ksir = new child('ksir',21,'man','hunan');
console.log(c);
  • 数组去重

    • 实现思路:
      • 声明一个函数实现数组去重,取名为unique;
      • 判断浏览器是否支持数组的indexOf方法
      • 如果不支持,就实现数组的indexOf方法,并且将其扩展到数组的原型对象上
      • 遍历数组,首先判断结果数组ret中是否含有当前遍历到的元素
      • 如果没有,就将当前元素添加到ret中
      • 循环结束,将ret返回

面试题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function foo(){
getName = function() { alert(1);};
return this;
}
foo.getName = function() { alert(2);};
foo.prototype.getName = function() { alert(3); };
var getName = function(){ alert(4);};
function getName() { alert(5); }

foo.getName();
getName();
foo().getName();
getName();
new foo.getName();
new foo().getName();
new new f00().getName();
赞 赏
微信扫一扫