// 1,默认绑定规则
function test1() {
console.log(this);
}
test1();
(function() {
console.log(this);
})()
默认绑定规则是指向window的,比如函数的独立调用,定时器,立即指向函数
// 2,隐式绑定规则
let obj1 = {
name: 'zhangsan',
foo: () => {
console.log(this, '+');
// function test2() {
// console.log(this);
// }
// test2()
}
}
obj1.foo()
console.log('--------------------------------------------');
let obj2 = {
name: 'zhangsan',
foo: function() {
console.log(this, '+');
function test2() {
console.log(this);
}
test2()
function test3() {
console.log(this);
}
return test3
}
}
obj2.foo()
obj2.foo()()
console.log('---------------------');
let bar1 = obj2.foo
bar1()
console.log('---------');
let bar2 = obj2.foo()
console.log('--------------------------------');
function test4() {
console.log(this);
}
let bar3 = {
foo: test4
}
function test5(fn) {
console.log(this);
fn()
}
test5(bar3.foo)
console.log("---------------------------------------------------------------------");
隐式调用一般是谁调用就会指向谁,但是向箭头函数旧特殊速,它没有自己的this,他中的this指向是上一个函数的this指向
// 3,显示转化
function test6() {
console.log(this);
}
test6.call(obj1, 1, 2, 3)
test6.apply(obj1, [1, 2, 3, 4, 5])
test6.bind(obj1)(1, 2, 3)
显示转化一般是依赖call,apply,bind的函数去改变this指向,call和apply的区别是传的参数不同,call使用的更多它传参是列表,apply传参是数组,而bind不同于二者它会返回一个新函数,然后显示转化的优先级高于隐式转化
//new实例化
function test7(b) {
this.a = b
}
let obj3 = new test7(3)
console.log(obj3.a);
console.log('-------------------------------');
let test8 = () => {
console.log(this);
}
let obj4 = {
f: test8
}
obj4.f()
new中的this一般都是指向新的实例化对象,它 的优先级是高于隐式转换和显示转化的,究其原因好像是new的过程中也调用了显示转化,所以如果有显示转化new中的显示转化会覆盖旧的显示转化。