JavaScript this

this

对象中的this

//对象属性中的this,指向window
//对象函数中的this,指向函数的调用者
// console.log(this);//window
        function abc(){
            // console.log(this);//window
        }

//对象中的this
var obj = {
    a:1,
    b:function(){
        // console.log(this);//指向当前调用对象obj
    },
    c:this.a,//指向window
}
obj.b();

var obj = {
    a:1,
    b:{
        c:this.a,//window
        d:function(){
            console.log(this);//当前调用对象b
        }
    }
}
obj.b.d();

回调函数中的this指向window

    //回调函数中的this指向window
    function ab(fn) {
        fn();
    }
    function cd() {
        console.log(this)//this指向window
    }
    ab(cd);

    //对象中既有回调函数,又有函数,看调用方式
    //obj对象直接调用,则指向调用者obj
    //回调函数方式调用指向window
    var obj = {
        a:function(fn){
            fn();
        },
        b:function(){
            console.log(this);
        }
    }
    obj.b();//指向调用者obj
    obj.a(obj.b);//指向window

事件函数,this指向侦听对象(箭头函数另论)

    document.addEventListener("click",clickHandler);
    function clickHandler(e){
        console.log(this);//指向被侦听的对象
        console.log(this === e.currentTarget);//true
    }

    //对象函数中存在事件,按事件的判定来
    var obj = {
        a:function(){
            document.addEventListener("click",this.b);
        },
        b:function(e){
            console.log(this);//指向document
        }
    }
    obj.a();

ES6类中的this

    // 对于ES6类
    // 静态方法中的this指向当前Class类.面向对象中,一般静态方法和属性不允许用this
    // 构造函数中的this指向实例化的对象
    // 非静态方法中的this指向实例化对象
    class Box {
        constructor() {
            this.b = 3;
            this.a = this.b;
            Box.b = 20;
            Box.a = Box.b;
        }
        play() {
            // 这里的this都是实例化的对象
            console.log(this.a);
        }
        static run() {
            console.log(this);
            // this
            // 因为使用static定义的方法,this指向为当前类名Box
            // 对于面向对象语言来说,一般在静态属性和方法中不允许使用this这个概念
        }
    }

ES5类

//构造函数:function Box(){}
//实例化类  var box = new Box();
function Box() {
    this.play();//构造中的this指向new出的对象
}
Box.s = 100;
Box.a = function () {
    //类似静态方法,这里面的this指向类Box
    console.log(this.s,this);//100,构造函数f Box
}
Box.b = 3;//类似静态属性
Box.prototype.play = function () {
    //this,在这里指向调用调用该方法的实例对象,如box.play(),this指向box
    console.log(this);//Box {}
}
Box.prototype.c = 10;
var b = new Box();
b.play();//Box {}
console.log(b);//Box {}
console.log(Box.a());//100 ƒ Box()

ES6箭头函数

所有箭头函数内的this指向,都是指向当前函数外的this指向
var obj = {
        a:function(){
            setTimeout(()=>{
                //本来setTimeOut的回调函数默认指向window
                //但因为是箭头函数,则将此处this指向setTimeout
                console.log(this);
            },0);
        }
    }

call apply bind

call、apply方法将函数中的this绑定为此call/applay方法的第一个参数
Array.prototype.slice.call(div);//将slice中的this全部指向div
Array.prototype.slice.apply(div);//将slice中的this全部指向div

bind将函数的this绑定给指定参数
var fn1 = obj.fn2.bind(div);//fn2函数中的this绑定为div
posted @ 2020-02-18 20:38  IslandZzzz  阅读(169)  评论(0编辑  收藏  举报