实例讲解JavaScript中的this指向错误解决方法
2019/6/27 22:21:32
本文主要是介绍实例讲解JavaScript中的this指向错误解决方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
看如下对象定义:
'use strict' var jane = { name : ‘Jane', display : function(){ retrun 'Person named ' + this.name; } };
这样能正常调用
jane.display();
下面的调用会出错:
var func = jane.display; func()
TypeError: Cannot read property 'name' of undefined
因为,this指向已经改变,正确的方式如下:
var func2 = jane.display.bind(jane); func2()
'Penson named Jane'
所有函数都有其特殊的this变量,如下面的forEach
var jane = { name : 'Jane', friends: ['Tarzan', 'Cheeta'], sayHiToFriends: function(){ 'use strict'; this.friends.forEach(function(friend) { // 'this' is undefined here console.log(this.name + ' says hi to '+ friend); }); } }
调用sayHiToFriends会产生一个错误:
jane.sayHiToFriends()
TypeError: Cannot read property 'name' of undefined
解决方案一:将this保存在不同的变量中
var jane = { name : 'Jane', friends: ['Tarzan', 'Cheeta'], sayHiToFriends: function(){ 'use strict'; var that = this; this.friends.forEach(function(friend) { console.log(that.name + ' says hi to '+ friend); }); } }
解决方案二:利用forEach的第二个参数,它可以给this指定一个值
var jane = { name : 'Jane', friends: ['Tarzan', 'Cheeta'], sayHiToFriends: function(){ 'use strict'; this.friends.forEach(function(friend) { console.log(this.name + ' says hi to '+ friend); }, this); } }
这篇关于实例讲解JavaScript中的this指向错误解决方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用js将ETH账户的资产打散其他账户web3
- 2024-09-27我轻松地将我的 React.js 应用程序翻译成了多种语言。下面是我是如何做到的... ??
- 2024-09-27?? 使用 useMemo 和 useCallback 加速 React:告别缓慢的重新渲染!??
- 2024-09-27Vue CLI多环境配置教程:新手入门指南
- 2024-09-27Vue CLI多环境配置教程:快速入门指南
- 2024-09-27Vue CLI教程:新手入门指南
- 2024-09-27Vue CLI教程:初学者快速入门指南
- 2024-09-27Vue3公共组件教程:入门与实践
- 2024-09-27Vue3公共组件教程:新手入门指南
- 2024-09-27Vue3教程:初学者快速入门指南