栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

实例讲解JavaScript中的this指向错误解决方法

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

实例讲解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);
  }
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/96205.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号