Javascript 原型、范围和承诺

Javascript 原型、范围和承诺,javascript,promise,Javascript,Promise,如何将Google的作用域绑定到fetch_page函数?我需要能够在promise和chains中将函数链接在一起 Google.prototype.search = function(keyword){ this.keyword = keyword || this.keyword; fetch_page().then(parse_page).then(function(){ console.log('done'); }); }); function

如何将Google的作用域绑定到fetch_page函数?我需要能够在promise和chains中将函数链接在一起

Google.prototype.search = function(keyword){
    this.keyword = keyword || this.keyword;

    fetch_page().then(parse_page).then(function(){
        console.log('done');
    });
});

function fetch_page(){
    // I wants to access google's this.keyword
}

function parse_page(){
    // I also wants to access google's this.keyword
}
有什么想法吗?

像这样

var google = new Google(); // return the class instance

google.keyword // get the public class variable called keyword

为了简单起见,我会选择:

fetch_page(keyword).then(function() {
    parse_page(keyword);
}).then(function(){
    console.log('done');
});
然后将
关键字
添加到两个外部函数的参数列表中

或者,只需在
Google.prototype.search
中内联这两个函数,以便它们共享相同的范围

第三种方法是让函数显式地将上下文设置为您的
this
对象:

var fetch = fetch_page.bind(this);
var parse = parse_page.bind(this);

fetch().then(parse).then(...);
Function#call
可用于调用
fetch_页面
,指定用作
的值:
fetch_页面。调用(此)

然后ES5的
函数#bind
或jQuery的
$.proxy
(我认为您使用的是jQuery,从您使用的承诺来看,但这是一个猜测-更新:我错了,但我会留下信息,以防使用jQuery的人找到答案)来创建一个绑定版本的
解析页面
(也就是说,当调用该函数时,将使用特定的
this
avlue调用
parse_page

功能#绑定

Google.prototype.search = function(keyword){
    this.keyword = keyword || this.keyword;

    fetch_page.call(this).then(parse_page.bind(this)).then(function(){
        console.log('done');
    });
});
请注意,
Function#bind
来自ES5,因此您需要检查您想要的所有浏览器是否都有它。如果没有,它是ES5功能之一,可以在旧浏览器上“填充”;搜索“ES5填充”以查找多个选项

jQuery的
$.proxy

Google.prototype.search = function(keyword){
    this.keyword = keyword || this.keyword;

    fetch_page.call(this).then($.proxy(parse_page, this)).then(function(){
        console.log('done');
    });
});

您是否尝试过
fetch_page.call(this).然后(function(r){console.log(“done”);})
?这是如何将第二个承诺与调用链接起来的。(this)。这不会触发函数而不是提供作用域吗?我真的不想在所有then函数之后再冒泡。没有其他方法绑定它吗?这也是正确的,但没有TJs答案那么完整。+1。@lededje我不想假设您正在使用jQuery@Alnitak:我首先包括ES5,然后将jQuery作为选项。(我错了,lededje没有使用jQuery,这是服务器端!):-)我使用的是承诺的io,但.bind起了作用。谢谢你的帮助。@lededje:啊,非常感谢!!:-)