补环境基础(二) this的作用和绑定规则
一.this的定义
this
指向当前代码执行的上下文对象,用于访问对象属性和方法,其值取决于调用方式而非定义位置。总的来说,this 就是函数运行时所在的环境对象。
二.this的绑定规则
2.1 默认绑定
非严格模式下
,this
指向 全局对象
function sayHello() {console.log(this);
}sayHello();
//this指向window(浏览器环境)
//this指向global(nodejs环境)
严格模式下
,this
指向 undefined
'use strict';
function sayStrict() {console.log(this); // undefined
}sayStrict(); // 独立调用,严格模式 -> undefined
2.2 隐式绑定
当函数作为某个对象的属性(方法)被调用时,this
会隐式绑定到该对象上。
const user = {name: "Alice",greet: function() {console.log(`你好,我是 ${this.name}`);}
};user.greet(); // ✅ 隐式绑定 → 输出:你好,我是 Alice
2.3 显式绑定
通过调用call
/apply
/bind
方法,强制将函数中的this
绑定到指定的对象,简而言之就是改变函数运行时的this
指向
2.3.1 apply和call的使用
apply:
apply
接受两个参数,第一个参数是this
的指向,第二个参数是函数接受的参数,以数组
的形式传入改变
this
指向后原函数会立即执行,且此方法只是临时改变this
指向一次
call:
call
方法的第一个参数也是this
的指向,后面传入的是一个参数列表
跟apply一样,改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次
call和apply的简单调用
obj = {"name":"调用对象"}function test1(name,height){console.log(name,height);console.log(this)
}test1.call(obj,123,456)
test1.apply(obj,[123,456])//输出
//123 456
//{ name: '调用对象' }
//123 456
//{ name: '调用对象' }
当第一个参数为null
、undefined
的时候,默认指向window
(在浏览器中)
fn.call(null,[1,2]); // this指向window
fn.call(undefined,[1,2]); // this指向window
2.3.2 bind的使用
bind方法和call很相似,第一参数也是
this
的指向,后面传入的也是一个参数列表(但是这个参数列表可以分多次传入)改变
this
指向后不会立即执行,而是返回一个永久改变this
指向的函数
function fn(...args){console.log(this,args);
}
let obj = {myname:"张三"
}const bindFn = fn.bind(obj); // this 也会变成传入的obj ,bind不是立即执行需要执行一次
bindFn(1,2) // this指向obj
fn(1,2) // this指向window
2.4 new绑定
new
操作符调用构造函数时,构造函数内部的this
,会自动指向新创建的那个对象实例。
function Person(name, age) {// new 绑定:this 指向新创建的实例对象this.name = name;this.age = age;this.introduce = function() {console.log(`大家好,我是${this.name},今年${this.age}岁。`);};// 没有显式返回对象,所以自动返回新创建的实例
}// 使用 new 调用 Person,触发 new 绑定
const alice = new Person("Alice", 30);
alice.introduce(); // 输出:大家好,我是Alice,今年30岁。
参考文章:
bind、call、apply 区别
JavaScript中this的五种绑定方式详解