1

I am trying to rewrite one of my useful JavaScript class with TypeScript. In my JavaScript class I use closure variable self for implementing private field. It is useful in event handlers, for example onkeypress, where important to know invoker of event and current instance of my class.

var MyClass = function (valueHolder) {
            var self = this;
            this.valueHolder = valueHolder;

            MyClass.prototype.DoUsefullactions = function (value) {
                alert(value);
            }

            MyClass.prototype.onclickForHolder = function (e) {
                var value = $(this).val(); //value from attached input
                self.DoUsefullactions(value);
            }

            MyClass.prototype.GetSelf = function () {
                return self;
            }

            this.valueHolder.onclick = this.onclickForHolder;
        }

I can't find how to make what closure variable what will be available for all methods of the class without this.self syntax in TypeScript and make true private members in JavaScript way.

2
  • 2
    Assigning properties to prototype in constructor function is not good. It'll assign this on every constructor call. Commented Oct 17, 2012 at 12:19
  • thank you, it's only for example Commented Oct 17, 2012 at 12:22

2 Answers 2

3

There's an alternative function syntax for this. Simply use:

MyClass.prototype.onclickForHolder = e => {
    var value = $(e.target).val(); //value from attached input
    this.DoUsefullactions(value);
}

this will refer to the outer this and TypeScript will add a self-type variable behind the scenes.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, i know this version for solving problem, i'am assuming abstract solution exists in this situation in TypeScript
1

try

 MyClass.prototype.onclickForHolder =(ev:Event) =>this.DoUsefullactions(this,ev);

1 Comment

It would be appreciated if you explain why he should try that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.