0

如何将 Google 的范围绑定到 fetch_page 函数?我需要能够在 promise-then 链中将函数链接在一起。

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
}

有任何想法吗?

4

3 回答 3

3

Function#call可用于调用fetch_page,指定要用作的值thisfetch_page.call(this)

然后是 ES5Function#bind或 jQuery $.proxy(我认为你正在使用 jQuery,从你使用的 Promise 来看,但这是一个猜测——更新:我错了,但我会留下信息以防使用 jQuery 的人找到答案)创建一个绑定版本parse_page(即,一个函数,当被调用时,将parse_page使用特定的thisavlue 调用)。

Function#bind

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 shim”以找到多个选项。

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');
    });
});
于 2013-09-29T09:27:01.907 回答
2

为简单起见,我会选择:

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

然后添加keyword到两个外部函数的参数列表中。

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

第三种方法是.bind将函数显式设置为您的this对象:

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

fetch().then(parse).then(...);
于 2013-09-29T09:21:14.300 回答
-3

像这样

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

google.keyword // get the public class variable called keyword
于 2013-09-29T09:19:16.170 回答