Skip to content

"this" is not detected correctly inside a function #12841

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
emilgpa opened this issue Dec 11, 2016 · 2 comments
Closed

"this" is not detected correctly inside a function #12841

emilgpa opened this issue Dec 11, 2016 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@emilgpa
Copy link

emilgpa commented Dec 11, 2016

TypeScript Version: 2.1.4

Code

function hi() {
    let link = <HTMLAnchorElement>document.querySelector("#link");
    link.onclick = function(e:Event) {
        this.href = "http://www.typescript.com"; //href not exists as property
    }
}

Expected behavior:

this inside link.onclick function should be a HTMLAnchorElement but it is not.

Actual behavior:

this is not a HTMLAnchorElement so I don't can to access to properties of a link as "href"

@aluanhaddad
Copy link
Contributor

The type definition for onclick looks like this

onclick: (this: HTMLElement, ev: MouseEvent) => any;

If you change it to

onclick: (this: this, ev: MouseEvent) => any;

then you get the expected behavior. Perhaps it should actually be the latter.

@mhegazy
Copy link
Contributor

mhegazy commented Dec 12, 2016

This is a duplicate of #12490

@mhegazy mhegazy added the Duplicate An existing issue was already created label Dec 12, 2016
@mhegazy mhegazy closed this as completed Apr 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

3 participants