实例讲解JavaScript中的this指向错误解决方法
程序员文章站
2024-01-12 17:04:16
看如下对象定义:
'use strict'
var jane = {
name : ‘jane',
display : function(){...
看如下对象定义:
'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); } }
上一篇: PHP字符串处理函数总结
下一篇: MySQL的用户设置与授权
推荐阅读
-
实例讲解JavaScript中的this指向错误解决方法
-
javaScript中的Promise对象语法、常用方法实例讲解
-
JavaScript 嵌套函数指向this对象错误的解决方法_javascript技巧
-
实例讲解JavaScript中的this指向错误解决方法
-
实例讲解JavaScript中instanceof运算符的用法
-
Javascript中函数绑定bind()的实例讲解
-
JavaScript 中的执行上下文和执行栈实例讲解
-
jQuery:delegate中select()不起作用的解决方法(实例讲解)
-
JavaScript中的Java式继承实例讲解
-
Javascript中toFixed计算错误(依赖银行家舍入法的缺陷)解决方法