2013-10-23 26 views
5

在下面的代码中,当从setTimeout调用somethingUseful.thisUsefulThing时,是否可以参考somethingUseful.thatUsefulThingJavaScript:功能词典:功能参考可以从它的词典中起作用吗?

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' 
+6

你是什么意思“全球范围”vs“范围的对象”?您的代码如同书面作品。 – user2736012

+1

请记住,当您执行'object.method()'时,'method'中的'this'的值将成为对'object'的引用。在创建对象和方法的时候或时间没有区别。重要的是*你怎么称呼这个方法。把同样的方法放在不同的对象上,从该对象调用它,'this'的值将引用新的对象。 'var o = {thatUsefulThing:function(){console.log(“I'm too too!”);}}; o.foo = somethingUseful.thisUsefulThing; o.foo(); //我也很有用' – user2736012

+0

那里,我编辑它直接反映我遇到的错误简而言之。 – Synthead

回答

3

要简单地回答你的问题,YES,thisUsefulThing可以访问thatUsefulThing

但是作为你的代码目前运行, '这' 是实际上不是全球性的,它是指对所有直接后代本身有用的东西。

当我用文字对象时,我通常按名称引用它们,而不是“本”,所以你的情况我会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() 
+1

是的,这就是我的想法,特别是当我发布的代码实际上工作,哈哈哈。如果愿意,请花点时间查看我编辑的问题。是的,JavaScript是一个(很多逾期)我的清单新的。 – Synthead

+1

为了解决您的问题,我仍然会将'this.thatUsefulThing()'更改为'somethingUseful.thatUsefulThing()' – Miles

1

只需将this的值绑定到somethingUseful即可。

setTimeout(somethingUseful.thisUsefulThing.bind(somethingUseful), 1000); 
+0

可能更适合修复对'this'的错误引用,而不是绑定。 – Miles

+0

@我生活在一场风暴之中其实我认为这完全相反。依赖变量名称是非常不灵活的,容易出错并且远非DRY。 – plalx

+0

这样想:如果你是绑定的,你已经再次键入变量名两次,加上方法和括号。听起来相当湿我。 – Miles