자바스크립트/Ext JS
[Cookbook Study Ch01]4. Scoping your functions
베니94
2013. 5. 22. 01:10
Ext.onReady(function() { /*** * Date : 2013.05.22 * Desc : scope에 대한 예제이다. * 동일 변수가 지역일 경우 전역일 경우, 또는 동일 함수가 지역일 경우 * 전역일 경우 이 scope에 따라 호출되는 변수, 함수가 달라지겠다. */ // 썩 좋은 예제같지는 않다. // 범위 체인은 자바 스크립트 변수를 확인하는 방법입니다. 당신은 그 안에 지역 변수로 선언되지 않은 함수 내에서 변수에 액세스하려고하는 경우, 자바 스크립트 엔진 (즉, 범위), 함수의 체인을 다시 통과합니다 //그 이름과 일치하는 변수를 찾고. 그것은 한 다음이 사용됩니다 발견하면, 그렇지 않으면 오류가 발생합니다. 또한이 지역 변수가 같은 이름의 전역 변수보다 우선적으로 적용된다는 것을 의미합니다. var myGlobalVar = 'Hello from Global Scope!'; function myFunction() { var myGlobalVar = 'Hello from MyFunction!'; console.log(this); alert(myGlobalVar); } // alert(myGlobalVar); // myFunction(); // alert(myGlobalVar); function MyClass() { console.log(this); this.myProperty = 'Hello'; } var myClass = new MyClass(); // alert(myClass.myProperty); // alert(this.myProperty); // create 'cat' object var cat = { sound : 'miaow', speak : function() { alert(this.sound); } }; // create 'dog' object var dog = { sound : 'woof', speak : function() { alert(this.sound); } }; // call 'speak' method on each // cat.speak(); // alerts 'miaow' // dog.speak(); // alerts 'woof' // Ext.bind를 사용하여 dog.speak함수의 scope를 cat클래스로 변경하여 // cat클래스의 speak함수가 실행되도록 하였다. // Ext.bind(dog.speak, cat)(); // alerts 'miaow' // 아래 소스는 정상적인 버튼을 생성하고 클랙했을 경우 scope에 해당하는 // text를 실행하도록 하였다 . 여기서 scope는 버튼 자체이므로 'My Test Button' 이겠다. var button = Ext.create('Ext.button.Button', { text : 'My Test Button', listeners : { click : function(button, e, options) { alert(this.text); // alerts 'My Test Button' } }, renderTo : Ext.getBody() }); // button.show(); // create our sample scope object var exampleObject = { text : 'My Test Object' }; // 버튼을 생성하며 클릭 이벤트에 대한 구현체를 Ext.bind로 scope를 위의 exampleObject로 변경하였다. var button = Ext.create('Ext.button.Button', { text : 'My Test Button', listeners : { click : Ext.bind(function(button, e, options) { alert(this.text); // alerts 'My Test Object' }, exampleObject) }, renderTo : Ext.getBody() }); button.show(); // 위의 2 번째 버튼과 동일하게 실행된다. var button = Ext.create('Ext.button.Button', { text : 'My Test Button', listeners : { click : function(button, e, options) { alert(this.text); // alerts 'My Test Object' }, scope : exampleObject }, renderTo : Ext.getBody() }); button.show(); }); // 출처 : Ext JS4 Web Application Development Cookbook