2013-09-29 4 views
0

Google의 범위를 fetch_page 함수에 바인딩하는 방법은 무엇입니까? 나는 약속에서 사슬을 잇는 기능을 함께 할 수 있어야합니다.프로토 타입, 범위 및 약속

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 
} 

아이디어가 있으십니까?

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

을 다음 두 개의 외부 함수의 매개 변수 목록에 keyword를 추가 :이

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

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

당신이'fetch_page.call (이) 그 때는 봤어 (기능 (R) {을 console.log ("완료를");})'? –

+0

전화로 두 번째 약속을 연결하는 방법입니다 (this). 범위를 제공하는 대신 기능을 트리거하지 않습니까? – lededje

답변

3

Function#call하는 것은 fetch_page를 호출하는 데 사용할 수 있습니다

세 번째 접근 방식은 .bind에 기능이 명시 적으로 this 개체로 컨텍스트를 설정하는 것입니다.

다음 ES5의 Function#bind 또는 jQuery의 $.proxy (난 당신이 사용하고있는 약속에서, jQuery를 사용하고 생각하지만, 그것은 추측   — 업데이트입니다 : 그리고 내가 잘못했다,하지만 난에 정보를 떠날거야 (답변을 찾을 경우 jQuery를 사용하는 사람들이) parse_page의 바인딩 된 버전을 만듭니다 (즉, 호출 할 때 parse_page을 특정 this avlue로 호출하는 함수).

Function#bind

: 당신은 당신이 그것을 가지고 싶은 모든 브라우저 있는지 확인하는 것이 좋습니다 그래서 Function#bind은 ES5에서 것을

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

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

참고. 그렇지 않은 경우, 구형 브라우저에서 "shimmed"수있는 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'); 
    }); 
}); 
+0

나는 promised-io를 사용하고 있었지만 .bind는 치료를했다. 당신의 도움을 주셔서 감사합니다. – lededje

+0

Promise-io는 서버 쪽 nodej이므로 모든 것이 좋습니다 :) – lededje

+0

@lededje : 아, 아주 !! :-) –

-3

단순화하기 위해 내가 갈 것입니다.

또는 Google.prototype.search 내의 두 기능을 인라인하여 동일한 범위를 공유 할 수 있습니다. fetch_page.call(this) : this로 사용할 값을 지정,

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

fetch().then(parse).then(...); 
2

처럼

+0

그 이후에 모든 기능이 있지만 거품을 내고 싶지는 않습니다. 그것을 바인딩 할 다른 방법이 있습니까? – lededje

+0

@lededje 업데이트보기 ... – Alnitak

+0

이것은 정확하지만 TJ 답변만큼 완벽하지는 않습니다. +1. – lededje