1

If I declare this in a class

class AlertConfigViewModel {
   DeleteAlert = function (item) {
        if (item) {
            if (confirm('Are you sure you wish to delete this item?')) {
                this.Alerts.remove(item);
            }
        }
        else {
            alert("something is wrong");
        }
    };
}

it ends up like this:

var AlertConfigViewModel = (function () {
    function AlertConfigViewModel(json) {
      this.DeleteAlert = function (item) {
            if(item) {
                if(confirm('Are you sure you wish to delete this item?')) {
                    this.Alerts.remove(item);
                }
            } else {
                alert("something is wrong");
            }
        };
    }
}

If I call AlertConfigViewModel outside the context of AlertConfigViewModel then the "this" is not AlertConfigViewModel which I thought it would since its inside function AlertConfigViewModel(

thomaux
  • 19,133
  • 10
  • 76
  • 103
FutuToad
  • 2,750
  • 5
  • 36
  • 63

3 Answers3

1

Why not just declare your function as a property of your class in the normal manner?

class AlertTest {

    private alerts:string = "these-alerts";

    TraceAlert():void{
       console.log(this.alerts); // Logs "these-alerts", wherever it's called from
    };
}

class CallTest {

    private alerts:string = "not-these-alerts";

    constructor() {
        var target = new AlertTest ();  // Creates an instance of your class, as you say.
        target.TraceAlert()
    }
}

var t:CallTest = new CallTest();
// Output: "these-alerts"

I'm not sure what the FuncName = function() syntax gives you, other than scoping problems.

Jude Fisher
  • 11,138
  • 7
  • 48
  • 91
1

Please take a look at solution posted here: TypeScript and Knockout binding to 'this' issue - lambda function needed?

"this" will always point to class instance if you define method body inside constructor - its a trick, but imo its quite clean solution.

Community
  • 1
  • 1
Slawek
  • 2,592
  • 1
  • 24
  • 26
  • 1
    It's not a trick per se, it's taking advantage of the closure that happens when the Function instance is created. I've used this many times to supply static DOM actions to my ViewModel objects. – Joel Cochran Mar 15 '13 at 12:26
0

I suspect you will only have one instance of this 'class', rendering the use of the this key-word obsolete.

With similar syntax try something like:

ClassName = {
    Alerts: someObject,

    DeleteAlert: function (item) {
        if (item) {
            if (confirm('Are you sure you wish to delete this item?')) {
                ClassName.Alerts.remove(item);
            }
        } else {
            alert("something is wrong");
        }
    }
}

And if you want instances, I'd go for another syntax...

apelsinapa
  • 575
  • 3
  • 9