关于js中this的指向问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
//    this是JS中的一个关键字, 代表函数运行时再其内部自动实现的一个内部对象,只能在函数内部调用
//    this的指向就是调用函数的那个对象
    function test(){
        this.x=1
    }
//    具体情况,具体分析,下面列出this的4钟情况
//    1          纯函数调用,this指向全局, window
    function test1(){
        this.x=1;
        console.log(this.x)
    }
    test1()//1
//    为了证明this这个时候是指向全局,
var x=100;
    function test2() {
        console.log(this.x)
    }
    test2();//100
//    同时因为this指向全局, 这个时候改变this.x的值,就可以改变全局下的x的值
    var a=20;
    function test3(){
        var a=10;
        this.a=0;
    }
    test3();
    console.log(a)//变成了0
//    但是可以改变this的指向
    var a1=10;
    function test4(){
        var _this=this;
        _this.a1=0;
    }
    console.log(a1);

//    2   函数作为一个对象的方法去调用,this就指向这个上级对象
    function obj(){
        console.log(this.x)
    }
    var o={};
    o.x=1;
    o.test=obj;
    o.test();//1

//    3  作为构造函数调用,通过这个函数生成一个新对象, 这样这个this旧指向这个新生成的对象
function test5(){
    this.x = 1;
}
var ob = new test5();
ob.x; // 1

//    4  apply调用,改变函数的调用对象,即改变this的指向, 第一个参数就代表改变后的调用这个函数的对象。即this所指向的
var xo = 0;
function testq(a){
    console.log(this.xo+a)
}
var ob={
    xo:1,
    m:testq
};
//ob.m.apply(); //0
//ob.m.apply(ob,[5])//6   apply把this的指向改变成ob自己。
//ob.m.call(ob,5)//6      call把this的指向改变成ob自己。
//无论call  和apply 都是改变指向后立刻就执行,调用
 var bindd=ob.m.bind(ob,5);
bindd();
//    bind是改变指向后,返回一个新的函数,然后再再次执行调用这个新的函数
</script>
</html>
原文地址:https://www.cnblogs.com/joesbell/p/5942175.html