<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button>按钮</button>
</body>
</html>
<script>
var btn = document.querySelector('button')
// 函数中的this永指向调用者
function fn () {
console.log(this)
}
// var fn = function () {console.log(this)}
// 1. window
// fn() // window.fn()
// 2. 事件
// btn.addEventListener('click', fn)
// 实现一个功能 当点击按钮让btn背景色在1s之后变红
btn.onclick = function () {
// this --> btn对象
// 方案一 借用变量
/* var that = this
setTimeout(function () {
// 定时器中的this默认指向的是window
// btn.style.background = 'red'
// this.style.background = 'red'
that.style.background = 'red'
}, 1000) */
// 方案二
setTimeout(function () {
// 通过bind改变了this的指向让this指向从默认的window指向btn
this.style.background = 'red'
}.bind(this), 1000)
// 方案三 ES6的箭头函数
setTimeout(() => {
// 箭头函数没有this指向
this.style.background = 'red'
}, 1000)
}
// bind/call/apply 借用函数同时改变this指向
// 当前这三个都是函数对象上的方法 fn.bind/call/apply
// 他们三个第一个参数的都是要改变的this指向
// 1. bind类 第二个参数是参数列表 不会立即帮我们调用
var ff = function (a, b) {console.log(this, a, b,'这是ff')}
// ff.bind({name: '松花江'}, 10, 12)() // bind()()
// 2. call 第二个参数也是一个参数列表 但是他会立即调用
// ff.call(['嗯'], 11, 13)
// 3. apply 第二个参数是数组参数 但是他会立即调用
// ff.apply(null, [13, 15]) // 此时的this是window null表示不改this指向
// Math.max.apply(null, [11, 99, 22. 66, 77])
// Math.max.apply({}, [11, 99, 22. 66, 77])
// 对象中的this
var obj = {
name: 'suibian',
say: function () {
console.log(this, this.name)
}
}
obj.say() // this指向obj
</script>