Javascript onclick function this value

The value of this in onclick for a button

Why is it that when I say onclick=foo() on my button and console.log(this) in the foo function, the this variable is pointing to the window ? Since technically onclick=foo() is defined on the button so when the onclick function is called it should automatically set the value of this to the button correct? I know how to fix this but I never understood why this is happening.

it should automatically set the value of this to the button correct? and I know how to fix this IMHO its design flaw but still make question off-topic

Since if I do onclick=foo(this) somehow the correct context of this is passed which is the button. But in this case, this is pointing to the button and this wasn’t pointing to the button in the question above.

In the element you have an attribute only, there has to be a wrapper function in the deeper implementation . Notice, that this refers to the element within the onclick attribute.

2 Answers 2

In languages like Ruby or Java, this (or in case of Ruby self ) will always point to the object in which your method is defined. So in Ruby if you are working on the foo method inside the Bar class, self will always point to the object which is the instance of the Bar class.

JavaScript works quite surprisingly here. Because in JavaScript function context is defined while calling the function, not while defining it! This is what can surprise many when coming to JS from different fields. Such late binding is a powerful mechanism which allows us to re-use loosely coupled functions in variety of contexts.

To answer your question, this , when called from an onclick event handler is executed by the global context.

in my opinion it is because you did not pass your button to your function like this :

Читайте также:  Class nav link html

while your code is like this:

and the entry of your function is empty:

so you should pass this to your function like this:

and because the value of this is not set by the call, this will default to the global object , which is window in a browser.

for more info please check this out.

Источник

onClick Function «this» Returns Window Object

I’ve come across a head scratching issue with my JavaScript application. If I write an element like this:

I get «undefined.» I am away how «this» is supposed to work in regards to attached functions. But, I am baffled because «this» is not picking up the element, but apparently defaulting to «window.» I can’t figure out why this is happening. Does anyone have an explanation?

Try searching first, please. There are many duplicates. this is «dynamically bound» to the receiver of the function, or to the global object (e.g. window ).

5 Answers 5

That’s because you aren’t passing a reference to this in the JavaScript function call. this in the JavaScript function doesn’t refer to the same object as in the onClick example. Try this instead:

this is set entirely by how a function is called (ignoring ES5 bind). The calling context (i.e. global or function context, which establishes scope) is irrelevant. If this is not set by the call, it will default to the global object in non-strict mode regardless of where a function was called, and this can be set to any object when called from any context (i.e. it has nothing to do with scope).

To add portability you could also use like so: Called function will inherit the calling element as «this».

The onclick attribute value is effectively wrapped in a function and called with the element set to this, e.g.

function anon() < /* attribute value */ >anon.call(element); 

When you put a function in the body, you are essentially getting:

Here, this within anon will be the element, but since foo is called without setting this , it will be undefined. In non-strict mode, this will default to the global object ( window in a browser). In strict mode, this inside foo will be undefined.

Читайте также:  Html display block heights

One solution is to pass an element reference to the function:

function foo(callingElement)

As other answers already mention, the value of this will depend on how the function that contains it is called. But since your example is about event handlers, I’d like to highlight what cjc343 said on the comments:

You may find it to be more sensible if you remove the inline event handlers.

That’s pretty simple, actually. Considering this HTML:

The following JavaScript will account for both removing inline handlers, and using delegation:

var list = document.getElementById('list'); list.addEventListener('click', function(evt)< console.log("this is the element the event is bound to: " + this.id); console.log("the event target is the clicked element: " + evt.target.id); >); 

That will work on all browsers compliant to the W3C event model, including IE9. For older IE, you have to use attachEvent instead of addEventListener , and prepend the event names with «on» . More details here.

Another option, so you don’t have to pass this as a param, is to use call or apply. It’s a built in mechanism to set the value of this within a function. Though I would point out, adding your event handlers directly to your html is a bit antiquated. You may want to check out a JS framework for event delegation (jQuery, Prototype, Dojo, YUI, etc.).

If you are new to JavaScript do not use the this or new keyword, because either you will get it wrong or your code will be unnecessarily inefficient and more complex. What you are trying to accomplish, though is the following:

In that example the click event of that list item fires a function named foo. The this keyword is passed in as a variable. The this keyword merely refers to the entity that called the function in question and if it cannot find that entity it will refer to the window object of the browser. In this case the entity that called the function is the list item node from the DOM.

Читайте также:  Adodb inc php deprecated

I still suggest never using this keyword in order to avoid this kind of confusion moving forward.

EDIT: Also, do not use a tagName property as this is not standard. Instead use the nodeName property.

Источник

What’s «this» in JavaScript onclick?

@JMCF125 He managed to be useful anyway. I Googled for how to get the element that was clicked on in an onclick event, and ended up here, where I found the answer.

@J3STER The «javascript:» prefix is incorrect in onclick. You can find the explanation in Tim Down’s answer below.

8 Answers 8

In the case you are asking about, this represents the HTML DOM element.

It refers to the element in the DOM to which the onclick attribute belongs:

The value of event handler attributes such as onclick should just be JavaScript, without any «javascript:» prefix. The javascript: pseudo-protocol is used in a URL, for example:

You should use the onclick=»func(this)» form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol «this» will refer to the window object rather than the element.

Interesting downvote, although I suppose strictly speaking this answer only offers advice around the question rather than directly answering the question.

@Dave: Fair enough. By the time I wrote this the main question was already answered. My answer should probably have been a comment but I suspect I may not have had enough rep to add a comment at the time. Live and learn.

In JavaScript this refers to the element containing the action. For example, if you have a function called hide() :

Calling hide with this will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.

For example, you may have this clicking a number in the HTML below will only hide the bullet point clicked.

Источник

Оцените статью