0

It is possible to use this javascript variable reffering to myObject in all occurences in the following code?

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();
});
SYNCRo
  • 450
  • 5
  • 21

2 Answers2

2

Yes, it's possible. Typically, you'd use Function#bind, which returns a new function that, when called, will call the original with a specific value for this. Function#bind is an ES5 feature present on all modern browsers; to support old browsers, it can be polyfilled.

Here's an example:

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

In this case, I think the simplest thing to do is just stash the object reference in a variable:

function MyObject() {
    var theObject = this;

    theObject.myProperty = "a property";

    // etc.

The variable theObject can then be used in all those other places to refer to the object that the constructor builds.

Pointy
  • 405,095
  • 59
  • 585
  • 614