**在普通函数的中的this指向**
function test() {
var a = 1;
console.log(this.a);
console.log(window.a)
}
test()
在严格模式下的this指向问题
var a = 1;
function test (){
'use strict';
console.log(this);
console.log(this.a);
}
test();
在 对象属性中方法中this指向问题
var obj = {
a : 1,
test: function () {
console.log(this);
console.log(this.a)
}
}
obj.test()
函数参数传递是this指向的问题
function test (a) {
this.a = a;
console.log(this.a)
console.log(window.a)
}
test(1)
function test (a) {
this.a = a;
console.log(this.a);
return undefined;
}
test.prototype.say = function () {
console.log(this.a)
}
test(1).say()
function test (a) {
this.a = a;
console.log(this.a);
}
test.say = function () {
console.log(123)
}
test.prototype.say = function () {
console.log(this.a)
}
test.say()
var oBtn = document.getElementById('btn');
oBtn.onclick = function () {
console.log(this);
this.innerHTML = "加载中...";
this.disabled = true;
var _self = this;
setTimeout(function(){
_self.innerHTML = "点击";
_self.disabled = false;
}, 2000);
setTimeout(function(){
this.innerHTML = "点击";
this.disabled = false;
}.bind(this), 2000);
setTimeout(() => {
this.innerHTML = "点击";
this.disabled = false;
}, 2000);
}
function Test () {
this.oBtn = document.getElementById('btn');
this.a = 0;
this.init();
}
Test.prototype.init = function () {
this.bindEvent();
}
Test.prototype.bindEvent = function () {
this.oBtn.addEventListener('click', this.btnClick.bind(this), false);
var _self = this;
this.oBtn.addEventListener('click',function() {
this.btnClick()
}, false);
}
Test.prototype.btnClick = function () {
this.a ++;
console.log(this.a);
}
new Test()
call/apply 改变this指向 并且立即执行
写法不算区别
call(context, 原函数的参数们依次排列);
apply(context, 原函数的参数集合 用数组装载);
bind 改变this指向 并返回一个新函数
写法同call
|