js中this的使用

来源:互联网 发布:ipad淘宝购物车打不开 编辑:程序博客网 时间:2024/05/18 00:00
<script>    /*    * this是js的一个关键字,在不同的使用场合,它的值也会发生变化;但是无论怎么变化,它本质上指的就是调用函数的那个对象。    * this在js中主要的四种用法:    * 1.在普通函数中使用;    * 2.作为对象方法来使用;    * 3.作为构造函数来使用;    * 4.call和applay调用;    * */    //1.纯粹的在普通函数中使用;    //在这里this指的是全局性调用;它的指针指向是window。    function test1(){        this.x1 =1;        //window.x1 =1;        console.log('this.x1 = '+this.x1);        //console.log('window.x1 = '+window.x1);    }    test1();//1    console.log('****************************');    var x2 = 10;//全局变量    function test2() {        console.log('x2 = '+x2);//10        console.log('this.x2 = '+this.x2);//10    }    test2();    //以上x2申明为全局变量,在函数test2中x2和this.x2结果一样,正说明this的指向是全局。    console.log('****************************');    var x3 = 100;    function test3() {        this.x3 = 0;//重新赋值    }    test3();    console.log(x3);//0    //以上同样x3申明为全局变量,看看通过改变this.x3是否能改变x3的值,结果显而易见,再次说明this的全局性。    //以上就是this在普通函数中的使用    console.log('****************************');    //2.作为对象方法来使用;    //在这里this指的是他的上一级对象。    var obj={        name:"hello",//对象属性        show:function(){//对象方法        console.log(this.name);        //console.log(this);//this指obj这个对象    }};    obj.show();    var objA={name:"world"};//申明新的对象objA,属性name:"world"    objA.show=obj.show;//把obj里面的show方法赋给objA    objA.show();//调用这个对象,此时的this指的是objA;    console.log('****************************');    //3.作为构造函数来使用;    //例子1    var  fnn=function(age){        this.age=age;        this.show=function(){            console.log(age+'岁');            //console.log(this);//fnn        }    };    var a=new fnn(20);//new一个新的对象a;会先生成一个空对象,然后调用方法,把this的替换成这个空对象    a.show();//调用a对象中的show方法。    console.log(a.age);//20    //例子2    var SomeClass = function(){        this.value = 100;        //console.log(this);    };    var myCreate = new SomeClass();    console.log(myCreate.value); // 输出100    //有人说:在 js 中,构造函数、普通函数、对象方法、闭包,这四者没有明确界线。界线都在人的心中,你觉得呢?。    console.log('****************************');    //4.apply和call调用;    /*     * apply和call的区别:     * 相同点是两个方法产生的作用是完全一样的(改变this的指向),第一个是函数运行的作用域;     * 不同点是方法传递的参数不同,apply(obj,[arg1,arg2…]);  call(obj,arg1,arg2)     * */    var fnn4=function() {        this.name = "hello";        console.log(this.name);//hello        this.show = function() {            console.log(this.name);//hello        }    };    var d = new fnn4();    d.show();//fnn4    //声明新的对象objD,重新复制name;    var objD = {        name: "objD"    };    d.show.call(objD);//call(objD)改变this指向    /*    *    obj.show=d.show();    *    obj.show();    *    delete obj.show();    * */    var x = 0;    function test4(){        console.log(this.x);    }    var o={};//声明o对象    o.x = 10;//属性X=10赋值;    o.m = test4;    o.m.apply(); //0 ,this默认指全局对象    o.m.apply(o); //10,this指o对象   /* var arr=[1,2,3,4];    var a=Math.min.apply(arr,arr);    console.log(a)*/</script>