this

作者: 王康_Wang | 来源:发表于2016-10-12 09:31 被阅读0次
    1. call, apply 有什么作用?有什么区别?

    call和apply用来直接指定this的绑定对象;
    区别是call直接传入参数,而apply传入的是数组;

    fn.call(context, p1, p2,...);
    fn.apply(context, [p1,p2,...]);
    

    代码题:

    1.以下代码输出是什么?
    var john = {
        firstName: "John"
    }
    
    function func() {
        alert(this.firstName + ": hi!")
    }
    john.sayHi = func
    john.sayHi()
    
    • 显示弹窗:John:hi!
    Paste_Image.png
    2. 下面代码输出的是什么?为什么?
    func()
    
    function func() {
        alert(this)
    }
    //window
    
    • 返回window对象;因为:
    • 声明提前,func()执行命令alert(this);
    • func()运行在全局作用域window下,故this指向window
    3. 下面代码输出什么?
    function fn0() {
        function fn() {
            console.log(this);
        }
        fn();
    }
    
    fn0();
    
    
    document.addEventListener('click', function(e) {
        console.log(this);
        setTimeout(function() {
            console.log(this);
        }, 200);
    }, false);
    // window
    // document
    // window
    
    • fn0中的this指向全局作用域;
    • document.addEventListener中的this指向document;
    • setTimeout中的this指向全局作用域。
    4. 下面代码输出什么?为什么?
    var john = {
        firstName: "John"
    }
    
    function func() {
        alert(this.firstName)
    }
    func.call(john)
    
    • 弹窗John
    • func.call(john)使得func中this指向john
    5. 下面代码输出什么,为什么?
    var john = {
        firstName: "John",
        surname: "Smith"
    }
    
    function func(a, b) {
        alert(this[a] + ' ' + this[b])
    }
    func.call(john, 'firstName', 'surname')
    
    • 弹窗:John Smith
    Paste_Image.png
    • 通过call方法将function中的this指向john
    6. 以下代码有什么问题?如何修改?
    var module = {
        bind: function() {
            $btn.on('click', function() {
                console.log(this) //this指什么
                this.showMsg();
            })
        },
    
        showMsg: function() {
            console.log('饥人谷');
        }
    }
    
    • 事件绑定的回调函数中第一个this指向$btn,第二个应该指向module,故需声明一个变量给this赋值,如下:
    var module = {
        var _this = this;
        bind: function() {
            $btn.on('click', function() {
                console.log(this) //this指什么
                _this.showMsg();
            })
        },
    
        showMsg: function() {
            console.log('饥人谷');
        }
    }
    

    相关文章

      网友评论

          本文标题:this

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