小程序中闭包问题
发布于 6 年前 作者 leiyuan 15717 次浏览 来自 问答

var user = ‘The Global’;

var obj = {

user: ‘The object’,

getUser: function (){

return function (){

return this.user;

}

}

};

Page({

/**

  * 页面的初始数据

  */

data: {

},

btn_run: function () {

console.log(obj.getUser()());

}

})

如上所述代码,在闭包中使用this对象调用obj对象中的user属性时,会报名undifine错误。

这是为什么?

VM1646:1 thirdScriptError

Cannot read property ‘user’ of undefined;at pages/index/index page btn_run function

TypeError: Cannot read property ‘user’ of undefined

    at http://127.0.0.1:63456/appservice/pages/index/index.js:8:18

    at e.btn_run (http://127.0.0.1:63456/appservice/pages/index/index.js:21:30)

    at e.<anonymous> (http://127.0.0.1:63456/appservice/__dev__/WAService.js:18:4907)

    at e.a (http://127.0.0.1:63456/appservice/__dev__/WAService.js:17:31002)

    at z (http://127.0.0.1:63456/appservice/__dev__/WAService.js:17:24941)

    at Function.<anonymous> (http://127.0.0.1:63456/appservice/__dev__/WAService.js:17:26562)

    at http://127.0.0.1:63456/appservice/__dev__/WAService.js:18:509

    at http://127.0.0.1:63456/appservice/__dev__/WAService.js:6:26768

    at e.(anonymous function) (http://127.0.0.1:63456/appservice/__dev__/WAService.js:4:4917)

    at a (http://127.0.0.1:63456/appservice/appservice:1008:9451)

3 回复

可以参考一下javascript中this的用法

小程序的页面内的全局变量,应该是需要放在data里的。可以去了解一下vue.js跟小程序的js还是比较相通的

请问这里是在干嘛,看不懂你在写什么,能讲解一下吗

var obj = {

user: 'The object',

getUser: function (){

return function (){

return this.user;

}

}

};

回到顶部