关于js中this指向问题

1 篇文章 0 订阅

this指向问题

总结:

1.this指向在函数调用中 this指向window(非严格)

2.在对象调用函数中 this指向调用函数的对象

3.在构造函数中 this指向实例出来的对象

4.在call,apply,bind中this 指向第一个参数

5.箭头函数中的this指向这个函数对象的外层对象

代码如下:

// this-用于访问当前方法所属的对象
// 普通函数
let obj={
    a:12fn(){
        console.log(this);// obj
    },
    fn: function(){
        console.log(this==obj)// true
    },
    // 箭头函数
    fn: ()=>{
        console.log(this==obj)// false
    }
}
// 直接写和后填里面没有任何区别
obj.fn=function(){
    console.log(this==obj); // true
};

// 指向调用它的对象
document.onclick=function(){
    console.log(this==document);// true
}

obj.fn();

let _this;
// 函数的this跟定义无关的,跟调用有关
function show(){
    conole.log(this);// window
    _this=this;
}  

// 1-直接调用--window||undefined
show();

// 当使用严格模式‘use strict’;// undefine
// 2.-挂载对象上,然后执行方法--对象
let arr=[1,2,3];
arr.fn=show;// arr
arr.fn();

//3-window
setTimeout(show,100;// 定时器本身属于window

// 4-构造函数(new) --当前构建出来的实例
new show();// show的实例

let date = new Date();
console.log(date instanceof Date);// true

let s = new show();

console,log(s=--_this);

// 5 -工具函数 call强制改变this值
show();// undefine
show.call(12);  // 12  把this变成12
show.call('asdfasdf');
show.call(new Date());
show.call({a: 12});

let arr=[1,2,3];

arr.forEach=function(cb){
    for(let i=0;i<this.length;i++){
        cb(this[i]);
    }
}
arr.forEach(function (item){
    console.log(this,item);// window||undefine
});
  • 注意:

对象之间的比较用==
数字之前的比较用===,同时比较数据类型和数值

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值