this

2016-10-12  本文已影响0人  王康_Wang
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()
Paste_Image.png
2. 下面代码输出的是什么?为什么?
func()

function func() {
    alert(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
4. 下面代码输出什么?为什么?
var john = {
    firstName: "John"
}

function func() {
    alert(this.firstName)
}
func.call(john)
5. 下面代码输出什么,为什么?
var john = {
    firstName: "John",
    surname: "Smith"
}

function func(a, b) {
    alert(this[a] + ' ' + this[b])
}
func.call(john, 'firstName', 'surname')
Paste_Image.png
6. 以下代码有什么问题?如何修改?
var module = {
    bind: function() {
        $btn.on('click', function() {
            console.log(this) //this指什么
            this.showMsg();
        })
    },

    showMsg: function() {
        console.log('饥人谷');
    }
}
var module = {
    var _this = this;
    bind: function() {
        $btn.on('click', function() {
            console.log(this) //this指什么
            _this.showMsg();
        })
    },

    showMsg: function() {
        console.log('饥人谷');
    }
}
上一篇 下一篇

猜你喜欢

热点阅读