4. javascript 中的THIS

THIS指向总结

  • window:
  • 1、直接在全局输出this;
  • 2、函数打印this,并直接调用;
  • 3、定时器中普通函数为window;
  • 4、匿名函数自执行;
  • 事件中的this:

哪个对象触发,this就是那个对象

  • 实例:

new 构造函数 -this 就是实例

  • 箭头函数:

this走定义箭头函数的域;

  • 对象中的this

let obj = {fn:function(){console.log(this)}}
1、给某个元q素绑定方法,当事件触发方法执行的时候,方法中的this是当前操作的元素本身;

2、当方法执行的时候,我们看方法前面是否有没有点,没有点的this是window或者是undefined,有点,点前边是谁this就是谁;

接下来我们通过一些例子来看下

var name='蓝蓝';
function fn(){
    console.log(this.name);
}
var obj={
    name:"你好世界",
    fn:fn
};
obj.fn(); //=>this:obj  =>你好世界
fn(); //=>this:window => 蓝蓝(非严格模式,严格模式下是undefined) window.fn()把window.省略了

(function(){
    //自执行函数中的this是window或undefined    
})();


let obj = {
    fn: (function () {
        // this:window
        return function () {
            console.log(this);
        };
    })()
};
obj.fn(); //=>this.obj  
let fn = obj.fn; //=>把小函数给fn
fn(); //=>this:window 

// 箭头函数this
function fn(){
    //this:window
    console.log(this);
}
document.body.onclick=function(){
    //this:document.body
    fn();
};

window.name = "WINDOW";
let fn = n => {
    console.log(this.name);
};
let obj = {
    name: 'OBJ',
    fn: fn
};
// FN所处的执行上下文中的THIS是WINDOW
fn(10); //=>this:window
fn.call(obj, 10); //=>this:window 不是我们预期的OBJ
document.body.onclick = fn; //=>this:window 不是我们预期的BODY
obj.fn(10); //=>this:window 

===箭头THIS
let obj = {
    name: 'OBJ',
    fn: function () {
        //=>this:obj 普通函数是有自己的THIS的
        let f = () => {
            console.log(this);  // obj 
        };
        f(); //=>this:obj
        return f;
    }
};
let f = obj.fn();   
f(); //=>this:obj;


let obj = {
    name: 'OBJ',
    fn: function () {
        //=>this:obj
        //=>原本期望的需求是:1S后把OBJ中的NAME改为'蓝蓝'
        /* setTimeout(function () {
            console.log(this);//=>WINODOW
            this.name = '蓝蓝';
        }, 1000); */

        /* let _this = this;//=>把需要的THIS提前用变量存储起来
        setTimeout(function () {
            _this.name = '蓝蓝'; //=>需要使用的时候拿出来用即可
        }, 1000); */

        setTimeout(() => {
            console.log(this); //=>OBJ
            this.name = '蓝蓝';
        }, 1000);
    }
};
obj.fn();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容