在下面的代码中,当从setTimeout调用somethingUseful.thisUsefulThing时,它是否可以引用somethingUseful.thatUsefulThing?
var somethingUseful = {
thisUsefulThing: function() {
this.thatUsefulThing();
},thatUsefulThing: function() {
console.log("I am useful!");
}
}
setTimeout(somethingUseful.thisUsefulThing,1000);
现在,我收到此错误:
Uncaught TypeError: Object [object global] has no method 'thatUsefulThing'
最佳答案
简单地回答你的问题,是的,这个有用的旅行可以访问那个有用的问题
但是当你的代码当前运行时,’this’实际上并不是全局的,它是对所有直接后代本身有用的东西的引用.
当我使用文字对象时,我通常用名字而不是’this’来引用它们,所以在你的情况下,我会用somethingUseful.thatUsefulThing()替换’this.thatUsefulThing()’
为什么?因为无论如何它在全球范围内运作!
编辑:
正如plalx在他对我的回答的评论中指出的那样,实现这个类的最佳实践(使用示例类成员)将使用函数类/原型并看起来像这样:
function SomethingUseful () {
this.member = 'I am a member';
}
SomethingUseful.prototype.thisUsefulThing = function () {
this.thatUsefulThing();
}
SomethingUseful.prototype.thatUsefulThing = function () {
console.log('I am useful,and ' + this.member);
}
usefulObject = new SomethingUseful();
usefulObject.thisUsefulThing(); // logs fine with access to this.member
setInterval(usefulObject.thisUsefulThing.bind(usefulObject),1000); // has access to this.member through bind()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。