0

Consider my following object and method:

function ModalPopupWindow() {
    this.Modal = false; 

    function __InitModalPopUp(height, width, title) {

        if(this.Modal != true){
            divOverlay.onclick = function() { window.parent.HideModalWindow(); };
        }
    }    
}

Whey I try to assess this.modal property inside the init function on a ModalPopupWindow object, 'this' is referencing to Window, not the object's property. How can I get that value?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • use "new " when you make the object – dandavis Oct 01 '14 at 23:44
  • How/where are you calling `__InitModalPopUp`? What `this` refers to depends on how the function is *called*. Learn more about it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Felix Kling Oct 01 '14 at 23:45

1 Answers1

0

There are several techniques, including a method named bind(). Another approach is to create a variable and bind it to the parent context before the function is called. I have seen people use a variable named underscore this (_this)

function ModalPopupWindow() {

//Capture the correct "this"
var _this = this;

this.Modal = false;

function __InitModalPopUp(height, width, title) {

    //Use _this here
    if(_this.Modal != true){
        divOverlay.onclick = function() { window.parent.HideModalWindow(); };
    }    
}

}

I recommend this article if you want to learn more about how JavaScript works and how to use bind(). http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

ahoffer
  • 6,347
  • 4
  • 39
  • 68