美文网首页
js中的this丢失问题

js中的this丢失问题

作者: 我的昵称在不在 | 来源:发表于2019-08-23 14:58 被阅读0次

    一、问题引入

        var people = {
            age:'18',
            sport : function (name){
                console.log(name);
            }
        };
        var p = people.sport;
        p('liming');
    
    这样可以执行没问题
    
    
        var getEle = document.getElementById;
        var div = getEle('div');
        console.log(div);
        
        这样执行有问题
      
    

    同样是用一个指针指向一个对象的方法,然后通过这个指针直接调用方法。1没问题2有问题

    二、对于问题的猜测

    
        var people = {
            age:'18',
            sport : function (name){
                console.log(name + this.age);
            }
        };
        var p = people.sport;
        p('liming');
        
        有问题
        
    

    猜测:代码3有问题。所以猜测可能是由于代码2中document的getElementById方法中用到了this,由于指针div指向这个方法,然后用div直接调用,导致getElementById方法内部this的指向由document变成了window,以至于会失败。

    三、尝试解决

        var getEle = (function (func) {
            return function () {
                return func.apply(document, arguments);
            }
        })(document.getElementById);
    
        var div = getEle('div');
        console.log(div);
        
    

    调用的时候把this重新绑定到document,可以正常获取div。

    欢迎交流!

    相关文章

      网友评论

          本文标题:js中的this丢失问题

          本文链接:https://www.haomeiwen.com/subject/poftectx.html