- 直接使用
function fn(data){
console.log(data);
}
fn('hello') //hello
//fn('hello') 等同于 fn.call(window,'hello'),此时 this 指向 window
- 函数作为对象的方法被调用时,谁调用就指向谁
let someone = {
name: '石昊',
intro: function (age) {
console.log(`${this.name}在${age}岁时就比海神唐三强了`);
}
}
someone.intro(6) //石昊在6岁时就比海神唐三强了
//someone.intro(6) 等同于 someone.intro.call(someone,6),此时 this 指向 someone
- 箭头函数没有自己的 this,指向上一级作用域的this
var name = '唐三'
var wife = {
name: '小舞',
fn: () => {
console.log(this.name);
}
}
wife.fn() //唐三
举个栗子
var name = '石昊'
var tiandi = {
name: '叶凡',
fn: function () {
console.log(this.name);
}
}
var other = tiandi.fn
other() //other.call(window) 石昊
tiandi.fn() //tiandi.fn.call(tiandi) 叶凡
var xian = {
name: '楚风',
fn: function (func) {
func() //func.call(window)
}
}
xian.fn(tiandi.fn) //石昊
xian.fn = tiandi.fn
xian.fn() //xian.fn.call(xian) 楚风