码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript中的this

时间:2017-07-22 19:56:48      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:window   bsp   png   set   技术分享   http   images   问题   输出   

JavaScript中的this指向问题

在JavaScript中,this是经常使用的一个关键字,按照规定,this指向调用者,即谁调用该对象,则this指向谁,但是this存在一个缺陷,当在一个函数中定义另一个函数时,内部函数的this不会指向外部函数,而是指向Window。

var f1 = function(){
        console.log(this);
        var if1 = function(){
            console.log(this);
        }
        func2(); 
    }
    func();

输出结果为

技术分享

可以看到,外部的函数f1和内部的函数if1的输出结果都是Window,内部函数的this并没有按照正常的规则指向外部的函数,而是指向了Window,这是我在之前的学习中经常遇见的问题。例如在一个对象中创建一个函数进行输出:

    var person = {
    name:‘Zhang3‘,
    age:100,
    setPerson:function(){
            console.log(‘name:‘+this.name+‘age:‘+this.age);
            var isetPerson = function(){
                console.log(‘name:‘+this.name+‘age:‘+this.age);
                console.log(this);
            }
            isetPerson();
        }

    }
    person.setPerson();

在这里定义了一个对象person在对象中定义了两个属性,name和age并且定义了一个函数setPerson,在函数中定义了另一个函数isetperson,输出结果:

技术分享

 

第一个是在setPerson中通过this.name和this.age输出的结果,第二行是在isetperson中通过this输出的结果,通过测试,第二行指向了Window。

这是js中的一个先天的缺陷,解决方法是通过转换变量,即先定义一个变量来存储this的值,然后在后续的函数中使用这个变量,这样就可以实现this的正确指向。这个变量一般使用that:

var person = {
    name:‘Zhang3‘,
    age:100,
    setPerson:function(){
            console.log(‘name:‘+this.name+‘age:‘+this.age);
            var that = this;
            var isetPerson = function(){
                console.log(‘name:‘+that.name+‘age:‘+that.age);
                console.log(that);
            }
            isetPerson();
        }

    }
    person.setPerson();

在setPerson中定义that变量,用于存储this,因为此时调用者仍然是person,所以this指向person,在内部函数中使用定义的变量that调用。

技术分享

这样就能得到我们想要的结果,并且that的值是我们定义的person对象(Object)。

JavaScript中的this

标签:window   bsp   png   set   技术分享   http   images   问题   输出   

原文地址:http://www.cnblogs.com/Hlong-ZY/p/7222075.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!