this 指向问题

this 指向问题

基本环境
function
function构造函数
箭头函数
call,apply,bind

function

原则:this永远指向运行时调用这个方法的对象

代码块
function fun(){
const text = ‘test’;
console.log(this.text); // undefined
console.log(this); // Window
}
fun();
window.fun(); // 这样写等价于
// 调用者是window,所以this指向window

代码块
function obj = {
text: ‘test’,
fun: function(){
console.log(this.text); // test
}
}
obj.fun();
// this指向这个函数的调用者,调用者是obj,那this就是obj

代码块
function obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a); // 12
}
}
}
obj.b.fun();
// 调用fun的是obj中的b,所以this指向obj中的b

代码块
function obj = {
a: 10,
b: {
a: 12,
fun: function(){
console.log(this.a); // undefined
console.log(this); // window
}
}
}
const j = obj.b.fun;
j();
// 把fun这个函数赋值给了j,再执行j的时候,调用者就变成了window,所以this是window

function构造函数

new 关键字会改变this指针的指向

代码块
JavaScriptfunction obj() {
this.x = ‘x’;
this.fun = function() {
console.log(this.x);// x
}
}
const o = new obj();
o.fun();
// new关键字将this指向了o,不太恰当的理解是o就是这个obj方法是等价的,里面的fun方法用function关键字定义的,用这个关键字定义的方法,里面用到的this会指向调用者,就是o,o里面有x这个属性,所以可以正常输出

箭头函数

原则:this 指向在定义时指定,非运行时指定。this指向的是其上一层作用域的this,另外对象不能形成独立作业域。


call apply bind

通过这三个方法都可以改变this的指向,区别是call和apply会立即执行,bind不会,call和apply的区别是后续接受的参数不同,call是连续参数,apply是数组。

代码块
JavaScriptconst obj = {
    a: 10,
    b: {
        a: 12,
        fun: function(){
            console.log(this.a); 
        }
    }
}
const j = obj.b.fun;
j();// undefined
j.call(obj);// 10
j.call(obj.b);// 12

//把this变成传入的对象
代码块
var obj = {
    a: 10,
    b: {
        a: 12,
        fun: function(){
            console.log(this.a); 
        }
    }
}
const j = obj.b.fun;
j();// undefined
j.apply(obj);// 10
j.apply(obj.b);// 12

//把this变成传入的对象
代码块
const obj = {
    a: 10,
    b: {
        a: 12,
        fun: function(){
            console.log(this.a); 
        }
    }
}
const j = obj.b.fun;
j();// undefined
let c = j.bind(obj);
c();// 10
c = j.bind(obj.b);
c();// 12

//把this变成传入的对象,但是不会立马执行,而是返回一个新的对象,想执行得去执行新的对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值