函数中的this指向问题
普通函数
function fn() {
console.log(this);
}
fn.call();
对象的方法
var o = {
sayHi: function() {
console.log(this);
}
}
o.sayHi();
构造函数
- 3.构造函数(this指向ldh这个实例对象,构造函数原型的this也指向这个实例对象)
function Star() {
console.log(this);
}
var ldh = new Star();
绑定事件函数
- 4.绑定事件函数(this指向btn这个按钮对象)
btn.onclick = function() {}
定时器函数
setInterval(function() {
console.log(this);
}, 1000);
立即执行函数
(function() {
console.log("立即执行函数");
})()
改变this指向的方法(call/apply/bind)
call
var o = {
name: "yzx",
}
function fn(a, b) {
console.log(this);
console.log(a + b);
}
fn.call(o, 1, 2);
function Father(uname, age, sex) {
this.uname = name;
this.age = age;
this.sex = sex;
}
function Son(uname, age, sex) {
Father.call(this, uname, age, sex);
}
var son = new Son("xxx", 18, 'male');
console.log(son);
apply
var o = {
name: "yzx",
}
function fn(arr) {
console.log(this);
console.log(arr);
}
fn.apply(o, ['yzx']);
arr1 = [1, 22, 6, 33, 9];
var max = Math.max.apply(null, arr1);
var min = Math.min.apply(null, arr1);
console.log(max, min);
bind
var o = {
name: "yzx",
}
function fn() {
console.log(this);
}
var f = fn.bind(o);
f();
bind方法的应用
var btn = document.querySelector('button');
btn.onclick = function() {
this.disabled = true;
setTimeout(function() {
this.disabled = false;
}.bind(this), 3000)
}
var btns = document.querySelectorAll('button');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function() {
this.disabled = true;
setTimeout(function() {
this.disabled = false;
}.bind(this), 3000)
}
}