javascript中this
前言
本文章主要描述this
一、在普通函数中、在HTML中、
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>javascript中this</h1>
<p onclick="fun1(this)">在普通函数中</p>
<p class="dom">事件注册dom1</p>
<script>
// this是谁调用函数,谁是函数中的this
// 01 在普通函数中的this
// 01.2 在html中调用 window
// 01.2 在dom1事件注册中:事件对象(dom)
var dom = document.querySelector(".dom")
dom.onclick = fun2
function fun2(){
console.log(this)
}
function fun1(el){
console.log(this,el);
}
// window.fun1();
</script>
</body>
</html>
二、在对象中全局函数中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>javascript中this</h1>
<p>在对象中</p>
<p>全局函数中</p>
<p>箭头函数中</p>
<script>
// this是谁调用函数,谁是函数中的this
// 02 对象中的this:对象本身
// 03.在全局方法中this:window[setInterval setTimeout]
// 04 箭头函数的this指向的是上一层作用域的this
var age = 50;
var obj = {
name:"zzz",
age:18,
say:function(){
console.log(this.age);
// alert(`大家好我的名字是${this.name},今年${this.age}`)
},
grow:function(){
setInterval(()=>{
this.age++;
console.log(this.age);
},3000)
}
}
// obj.say()
// var fn = obj.say;
// fn();
obj.grow()
</script>
</body>
</html>
三、call-apply-bind中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>javascript中this</h1>
<p>call-apply-bind中</p>
<script>
// this是谁调用函数,谁是函数中的this
// 02 对象中的this:对象本身
// 03.在全局方法中this:window[setInterval setTimeout]
// 04 箭头函数的this指向的是上一层作用域的this
// call与apply-bind中this指向的函数call的i第一个参数
function add(a,b){
console.log(this,a,b);
}
// call与apply都是执行一个函数,使用第一个参数冒充函数中this
//
// add.call({name="zzz"},4,5);
// apply的传参方式用数组
// add.apply({name:"zzz",age:18},[8,7])
// bind 把bind的第一个参数作为this,创建一个+新的函数,并可以指定默认参
var fn = add.bind({eye:2,leg:2},10,5);
// fn(5);
fn();
// 把函数简化参数的这种方式称为函数的柯里化
</script>
</body>
</html>