this:
当普通函数在执行时,js解析器每次都会传递一个隐含的参数 这个参数就是this
(隐含的参数不需要定义 不需要传参数 是引擎器底层内置的 直接使用)
-this 通常会指向一个对象 会根据函数调用的方式不同而不同
-this指向window
1.以函数形式调用时,this指向的是window
2.通过对象名.方法名调用函数时的this指向是当前方法名的对象(指向的当前调用方法的对象)
---通过this的指向可以在方法中引用当前调用方法的对象
当将函数 赋值给一个对象的时候
可以使用对象名.方法名( )调用函数
function fn() {
}
fn( )
cosnt obj = {name:'代普是狗'}
const obj.test =fn 此时将fn赋值给一个对象.方法 通过调用对象.方法名
此时obj.test对象方法名就代表这个函数
![](https://i-blog.csdnimg.cn/blog_migrate/0b5487ccd35827ba72c52f6b9e88e49d.png)
<script>
function fn() {
//console.log(this === window)
//console.log('fn打印', this === obj)
console.log('我是函数fn1', this)
/* this指向Object 里面包含name:孙悟空 test:fn() 此时this指向事件对象*/
}
const obj = { name: '孙悟空' }
obj.test = fn
const obj2 = { name: '猪八戒', test: fn } // 此时obj2中的test方法中存储的是fn()函数
// 函数调用 test中存储的是函数fn 对象堆中赋值的是地址
obj.test() //obj.test中存储的就是函数fn 可以通过obj.test调用函数fn
console.log(obj.test() === fn()) //此时它们使用的是同一个堆地址 返回true
console.log(obj2.test() === obj.test())//true
</script>