如何在JavaScript对象的嵌套内部函数中调用对象自身方法
解决嵌套函数中调用外层对象方法的问题
首先得搞清楚为啥你原来的写法行不通:在func_Inner里,this指向的是它所属的对象x,而不是外层的obj,所以直接this.func2()肯定找不到对应的方法,你写的this.func2().bind(obj)也搞错了顺序——得先把func2的this绑定到obj再调用,而不是调用之后再绑定。
下面给你几种实用的实现方式:
方法1:保存外层this到变量(经典写法)
在func1里先把当前的this(也就是obj)存到一个变量里,比如self或者that,这样内层函数就能通过这个变量拿到obj的引用:
obj = { prop1 : 0, prop2 : 1, func1 : function (){ var self = this; // 把obj的引用存到self里 var x = { func_Inner : function(){ self.func2(); // 用self调用func2,此时self指向obj } } x.func_Inner(); // 注意你原来写的x.f()应该是笔误,改成x.func_Inner() this.func2() }, func2 : function (){ console.log(this) console.log(this.prop1,this.prop2) } }
方法2:使用箭头函数(ES6+ 简洁写法)
箭头函数不会绑定自己的this,它会继承外层作用域的this,所以把func_Inner写成箭头函数的话,里面的this就会直接指向func1里的this(也就是obj):
obj = { prop1 : 0, prop2 : 1, func1 : function (){ var x = { func_Inner : () => { // 换成箭头函数 this.func2(); // 这里的this就是obj } } x.func_Inner(); this.func2() }, func2 : function (){ console.log(this) console.log(this.prop1,this.prop2) } }
方法3:调用时手动绑定this
如果你不想修改函数定义,可以在调用func2的时候用call、apply或者bind来强制指定this指向obj:
obj = { prop1 : 0, prop2 : 1, func1 : function (){ var x = { func_Inner : function(){ // 用call直接指定this为obj obj.func2.call(obj); // 或者用bind创建绑定后的函数再调用 const boundFunc = obj.func2.bind(obj); boundFunc(); // 如果obj是全局可访问的,直接调用也行 obj.func2(); } } x.func_Inner(); this.func2() }, func2 : function (){ console.log(this) console.log(this.prop1,this.prop2) } }
方法4:把obj作为参数传递给内层函数
如果obj不是全局变量,也可以把它作为参数传给func_Inner:
obj = { prop1 : 0, prop2 : 1, func1 : function (){ var x = { func_Inner : function(targetObj){ targetObj.func2(); } } x.func_Inner(this); // 把当前的this(obj)传进去 this.func2() }, func2 : function (){ console.log(this) console.log(this.prop1,this.prop2) } }
内容的提问来源于stack exchange,提问作者Amir Shahbabaie
相关产品推荐
相关产品推荐

