改变this 指向的3种方法
2024-10-02 19:20:39
1.在函数内部声明一个that,然后将this赋值给that,
var that=this;
最后用that 代替this使用
<!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> </body>
<script>
const team={
members:["Herry","hrll"],
teamName:"Es6",
teamSummary:function() {
var that=this;
return this.members.map(function(member) {
return `${member}隶属于${that.teamName}`
})
}
}
console.log(team.teamSummary())
</script>
</html>
2.用bind方法,绑定外部的this
<!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> </body>
<script>
const team={
members:["Herry","hrll"],
teamName:"Es6",
teamSummary:function() { return this.members.map(function(member) {
return `${member}隶属于${this.teamName}`
}.bind(this))
}
}
console.log(team.teamSummary())
</script>
</html>
3.直接使用箭头函数
<!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> </body>
<script>
const team={
members:["Herry","hrll"],
teamName:"Es6",
teamSummary:function() { return this.members.map((member)=> {
return `${member}隶属于${this.teamName}`
})
}
}
console.log(team.teamSummary())
</script>
</html>
3个显示效果:
最新文章
- 半吊子学习Swift--天气预报程序-获取天气信息
- ReSharper.8.0.14.856注册码
- iOS 直播-闪光灯的使用
- MongoDB基本使用
- 第七篇——Mobile Apps,软件的曙光。
- C语言实现粒子群算法(PSO)二
- Entity Framework在WCF中序列化的问题
- APP图标和启动页
- php:获取浏览器的版本信息
- SQL Server常用命令
- 【最小生成树】BZOJ 1196: [HNOI2006]公路修建问题
- arcgis engine 开发之QI
- 测试通过Word直接发布博文
- WEB 开发所用的网站
- UITabBarController中自定义UITabBar
- NVL NVL2 NVLIF
- 【转载】最全的面试题目整理(HTML+CSS部分)
- ThinkPHP 实现验证码渲染、校验、点击刷新
- [蓝桥杯]PREV-19.历届试题_九宫重排
- webpack安裝和卸載
热门文章
- 自己写IRP,做文件操作,遇到的坑
- springMVC框架入门案例
- Java中super关键字的位置
- 08-01-json-loggin-模块
- react-router v3和v4区别
- putty字体和颜色修改
- cdn 链接
- docker学习路线图
- [bzoj2752]高速公路 题解(线段树)
- 20140729 while((*pa++=*pb++)!=&#39;\0&#39;) 合并数组代码 C++类型转换关键字 封装 多态 继承