2014-12-28 1 views
0

다음 코드의 모든 경우에 this myObject에 javascript 변수를 사용할 수 있습니까?JS - 'this'를 사용하여 다양한 범위의 동일한 객체를 참조하는 방법?

jsFiddle - open console

function MyObject() { 
    this.myProperty = "a property"; 

    console.log("1 - this is %o (%s) in MyObject declaration", this, Object.prototype.toString.call(this)); 
    (function poll() { 
     console.log("2 - this is %o (%s) in poll function", this, Object.prototype.toString.call(this)); 
     setTimeout(function() { 
      console.log("3 - this is %o (%s) in setTimeout function", this, Object.prototype.toString.call(this)); 
      $.ajax({ 
       url: "/echo/json/", 
       dataType: "json", 
       success: function(data) { 
        console.log("4 - this is %o (%s) in ajax.success function. We have some data returned: %o", this, Object.prototype.toString.call(this), data); 
       }, 
       complete: poll 
      }); 
     }, 1000); 
    })(); 
}; 
$(document).ready(function() { 
    var myObject = new MyObject(); 
}); 

답변

2

예, 그것은 가능합니다. 일반적으로 Function#bind을 사용하면 호출 할 때 this의 특정 값을 가진 원본을 호출하는 새 함수를 반환합니다. Function#bind은 모든 최신 브라우저에있는 ES5 기능입니다. 예전의 브라우저를 지원하기 위해서, 그것은 다중화 될 수 있습니다. 내가 할 수있는 가장 간단한 것은 그냥 변수에 개체 참조를 숨길 생각이 경우

function Foo(name) { 
 
    this.name = name; 
 
    setTimeout(function() { 
 
    snippet.log("this.name = " + this.name); 
 
    }.bind(this), 0); 
 
// ^^^^^^^^^^^---- Note 
 
} 
 

 
var f = new Foo("foo");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

0

: 여기

은 예입니다

function MyObject() { 
    var theObject = this; 

    theObject.myProperty = "a property"; 

    // etc. 

그런 다음 다른 모든 장소에서 변수 theObject을 사용하여 생성자가 빌드하는 객체를 참조 할 수 있습니다.

관련 문제