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个显示效果: