简体   繁体   中英

Why doesn't the “this” keyword work here?

<button onclick="test()">Will it work?</button>


function test() {
this.innerHTML = "It works!";
}

The button calls the function test, so it should be affected by the "this" keyword.

Pass it to the function

<button onclick="test(this)">

function test(btn) {
    console.log(btn);
    btn.innerHTML = "it worked";
}

http://jsfiddle.net/KV27W/1/

From the MDN documentation :

Inside a function, the value of this depends on how the function is called.

Simple call

 function f1(){ return this; } f1() === window; // global object 

In this case, the value of this is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object.

So, whenever you call a function as func() , this refers to the global object. And that's exactly what you are doing here:

onclick="test()"

You are right that this inside an event handler refers to the element the handler is bound to, but test is not the event handler, it is in the body of an event handler. The handler generated from the attribute value will look like

function(event) {
    test();
}

So you see, it's a "simple call", so there is no question about what this refers to.


If you want to have it refer to the button, then you can use .call , to call test and explicitly set this to the passed value:

onclick="test.call(this)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM