【发布时间】:2012-12-10 20:10:09
【问题描述】:
我有此代码用于我想使用的新闻源。
我希望它看起来像这样:
function News(){
//Load new comments every 5 sec
setTimeout((function(){
console.log(this); //Returns Object #News
this.loadNewsFeed();
}).call(this),5000);
this.loadNewsFeed = function(){
// Implementation here
}
}
这里的问题是它说对象新闻没有一个名为loadNewsFeed的方法!
如果我将匿名函数放在对象 News 之外,我已经让它工作了。
像这样:
var news = new News();
//Load new comments every 5 sec
(function loopNews(){
news.loadNewsFeed();
setTimeout(loopNews,5000);
})();
那么我该如何在对象News中做到这一点?
【问题讨论】:
-
用
.bind替换.call -
MDN 详细介绍了如何处理“这个”问题。
-
但是你必须知道
binddeveloper.mozilla.org/en-US/docs/JavaScript/Reference/…需要的浏览器支持
标签: javascript oop function settimeout infinite-loop