如何将后代函数绑定到顶级父对象?
this.site
在我的例子中是未定义的。
如果我不使用.bind(),它指向.next
(它的父级),而不是顶级对象。 有没有办法让this
总是指顶级对象exports
?
var exports = { site: site, results: { next: function($){ debugger; console.log('Site: ', this.site); return this.site + $('.foo').attr('href'); }.bind(exports), } }; module.exports = exports;
你不能在这个时候使用.bind
,因为这个对象还在被构造, exports
没有值(或者至less不是你想要的)。 创build对象后 ,必须绑定该函数。 即
exports.results.next.bind(exports);
或者你重构你的代码,并使用现有的exports
对象:
exports.site = site, exports.results = { next: function($){ debugger; console.log('Site: ', this.site); return this.site + $('.foo').attr('href'); }.bind(exports), };
或者你只是使用exports
而不是像这样的adeneo提到 。 在你的情况下使用this
exports
没有什么好处。