JavaScript中函数的调用和this的指向

25次阅读

共计 451 个字符,预计需要花费 2 分钟才能阅读完成。

欢迎纠正和补充
函数的调用和 this 的指向
1. 普通函数调用 this 指向 window
function fn() {
console.log(this);
}
window.fn();

2. 方法调用 this 指向 调用该方法的对象
var obj = {
fun: function () {
console.log(this);
}
}
obj.fun();

3. 作为构造函数的调用 构造函数内部的 this 指向由该构造函数创建的对象
var gf = {
name : “tangwei”,
bar : “c++”,
sayWhat : function() {
console.log(this.name + “said:love you forever”);
}
}

4. 作为事件的处理函数 触发该事件的对象
btn.onclick = function () {
console.log(this);
}

5. 作为定时器的参数 this 指向 window
setInterval(function() {
console.log(this);
}, 1000);

总结:函数内部的 this,是由函数调用的时候来确定其指向的

正文完
 0