2012-11-29 2 views
0

이것이 작동하지 않는 이유를 말씀해 주시겠습니까? 예상대로동일한 객체의 메서드에서 속성을 참조하려면 어떻게해야합니까?

post.url = '<?php echo BASE_ADMIN . $postType ?>'; 

$(document).ready(function() { 

    $("#listing").aJqueryPlugin({ 
    ... 
    // Buttons and their callbacks 
    buttons : [ 
     {name: 'Add', bclass: 'add', onpress : post.add}, 
     {name: 'Edit', bclass: 'edit', onpress : post.edit}, 
    ], 
    ... 
}); 

라인

post.url = ....

동작합니다을 : 다른 코드에서

var post = { 
    url: 'http://myurl.com', 
    add: function() { 
     window.location = this.url + '/add'; 
    }, 
    edit: function() { 
     window.location = this.url + '/edit'; 
    } 
}; 

어딘가합니다 ( 키워드를 참고). 속성이 인 게시물이 업데이트되었습니다.

그러나, 나는이 클릭하면 또는 편집 버튼을 추가하고 내가 그 기능을 입력 this.url정의되지 않은이 때문에 참조 버튼 대신 포스트 개체입니다. 왜? 그러면 URL 속성을 콜백에서 참조하려면 어떻게해야합니까?

+2

"클로저"또는 "Function.bind"를 참조하십시오. –

+0

이것은 클로저와 관련이 없지만 실행 컨텍스트와 관련이 있습니다. – Christoph

+0

[Javascript : Object literal reference of this '] 대신 자신의 키 함수에'Literal reference '가 중복 될 수 있습니다. http://stackoverflow.com/questions/10711064/javascript-object-literal-reference-in-own-keys-function-instead -of-this) – Bergi

답변

2

jQuery를 사용하고 있으므로 $.proxy을 사용할 수 있습니다.

{name: 'Add', bclass: 'add', onpress : $.proxy(post, "add")}, 
    {name: 'Edit', bclass: 'edit', onpress : $.proxy(post, "edit")}, 

문자열로 명명 된 개체의 메서드를 호출하는 새 함수를 반환합니다.


효과적으로을하고있어 :

{name: 'Add', bclass: 'add', onpress : function() { 
              return post["add"].apply(post, arguments); 
             }, 
{name: 'Edit', bclass: 'edit', onpress : function() { 
              return post["edit"].apply(post, arguments); 
             }, 

함수에서 this의 값은 함수가 호출 방법에 의존하기 때문에, 당신은 때때로 당신이 얻을 수 있도록 대체 수단이 필요 올바른 값.


당신은 또한 당신이 당신을 알고 항상 this 그 객체를 참조하려면, 원래 객체에서 이러한 설정할 수 있습니다.

var post = { 
    url: 'http://myurl.com' 
}; 
post.add = $.proxy(function() { 
    window.location = this.url + '/add'; 
}, post); 
post.edit = $.proxy(function() { 
    window.location = this.url + '/edit'; 
}, post); 

이 직접 원하는 값 this 다음 기능을 전달할 수 $.proxy의 다른 서명을 이용한다.

+0

확장 코드에'return'을 추가해야합니다 – Bergi

+0

답장을 보내 주셔서 감사합니다! 이 기능은 ** 추가 ** 및 ** 수정 기능 ** 내부의 ** ** ** 창이 ** 참조되므로 약간 조정 한 후에 작동합니다. 그래서 나는 this.url + "/ add" post.url + "/ add"을 변경해야했습니다. –

+0

@Bergi : 좋은 지적. 업데이트 및 감사합니다 .. –

관련 문제