Skip to content

Type safety of "this" is potentially misleading in class methods #1787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
nfriend opened this issue Jan 23, 2015 · 1 comment
Closed

Type safety of "this" is potentially misleading in class methods #1787

nfriend opened this issue Jan 23, 2015 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@nfriend
Copy link

nfriend commented Jan 23, 2015

Given the following:

class TestClass {

    myTestObject = {
        message: 'It worked!',
    }

    myTestMethod() {
        console.log(this.myTestObject.message);
    }
}

var myTestClassInstance = new TestClass();
myTestClassInstance.myTestMethod.apply({});

The compiler assumes that the scope of this is the instance of the TestClass. However, if the method is called via .apply(), as in the example above, it is possible to hijack the this scope of the method.

This is a bit of an edge case, since most TypeScript code shouldn't be circumventing the type safety by using the .apply() method. However, some third-party JavaScript libraries rely on the .apply() method, which undermines confidence in the this keyword.

The fix is to redefine the method as a property using the fat arrow syntax, i.e.:

myTestMethod = () => {
    console.log(this.myTestObject.message);
}

Perhaps the compiler should only enforce type safety on this if the method is defined such that the this keyword is lexically scoped?

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 23, 2015
@RyanCavanaugh
Copy link
Member

See #15.

@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants