面向对象day4

上下文模式

函数的四种调用模式

  • 普通函数执行
    • this -> window
    • 声明一个函数后,就直接调用
  • 方法调用模式
    • this -> 该方法的调用者
    • 通过一个对象来调用方法
  • 构造函数模式
    • this —> 当前创建出来的对象
    • 配合new操作符来调用函数
  • call/apply(上下文)模式
    • this -> 用户动态指定的
      • 指定call or apply 方法的第一个参数
    • 区别:
      • <fn>.call(thisObj, arg1, arg2, ...,argN):thisObj为 this的指向。之后为形参列表,就是fn在执行时的实参列表
      • <fn>.apply(thisObj, [实参]): thisObj 为 this的指向,数组参数为 fn在执行时的实参
    • 注意:在非严格模式下,如果thisObj 赋值为 null 或者不传实参,此时this -> window 对象,就相当于 普通函数执行模式。
### 上下文模式的应用

+ 1 数组的合并
    - `Array.prototype.push.apply(arr1, arr2);`
+ 2 借调方法(函数)
   - 借用构造函数 
    
1
2
3
4
5
6
7
8
9
10
function parent(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

function child(name, age, gender, address) {
parent.call(this, name, age, gender);
this.address = address;
}
- 借用原生方法 + 求数组中的最大值 + 获取内置对象类型 + 将伪数组变成真数组
文章目录
  1. 1. 上下文模式
    1. 1.1. 函数的四种调用模式
|