想动态改变Label显示的文字,这样怎么不行?

start() {

    this.ttimer(3000)

/////3秒后想让label 显示 6,报错
},

ttimer(time) {

    setTimeout(function () {

        a = 6

        this.node.getComponent(cc.Label).string = a

    }, time);

},

////// 错误:
assets\js\NewScript.js:45 Uncaught TypeError: Cannot read property ‘getComponent’ of undefined
at eval (eval at (quick_compile.js:238), :50:17)

试着这么写下

setTimeout(() = >
{
}, time)

谢谢,这样可以,到底错在哪?新手不太懂啊。
主要是回调函数的使用吧,

建议先学一下的js的this,搞清楚运行期绑定到底是怎么回事

settimeout这个函数是会改变作用域的,所以你在这个函数体里面不能直接用this
settimeout(){ function () {this .xxx。。。} },这个里面的this是指settimeout这个函数,那么this.node就不存在啊,也就没有label这个组件了,所以报错。
()=>{ }这个东西叫箭头函数,他会继承上级的环境,也就是this是可用的。
或者你可以这么写:
let self = this;
setTimeout(function () {
a = 6;
self .node.getComponent(cc.Label).string = a;
}, time);
另外记住别学那些人自作聪明,语句最后的分号一定要写上去。

1赞

非常感谢,总算搞 明白了。