0

I have the following html code

<a href="javascript:update(this)">Val1</a>

<a href="javascript:update(this)">Val2</a>

And the function

function update(obj) {
     alert(obj); // I expect to get a tag object but I am getting Window Object
    //do something

}

Now I would expect to get object referring to a tag, but I get Window Object. Can some one tell me why object referring to a tag is not passed

coder hacker
  • 4,819
  • 1
  • 25
  • 50
  • **window**.location.href – T J May 15 '14 at 08:13
  • This is not a duplicate of http://stackoverflow.com/questions/2842116/reliable-way-of-generating-unique-hardware-id The question there is "how." The question *here* is "why." – T.J. Crowder May 15 '14 at 08:17

2 Answers2

2

Can some one tell me why object referring to a tag is not passed

Because this isn't an event attribute, it's a URL. The code in URLs using the javascript: pseudo-protocol is run as global code, with this referring to the global object, just like code in script elements (that don't use "use strict") is.

If you were using an event attribute, like onclick, then the code would be run as though it were in a function at global scope with this set to the element and an in-scope event variable referring to the current event.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You are visiting a javascript: scheme URI and not firing an event in the context of an Element object.

<a href="sensible_fallback.html" onclick="return update(this)">Val1</a>

function update(element) {
    alert(element);
    return false;
}

… but this is 2014, so don't use intrinsic event attributes.

<a href="sensible_fallback.html" id="foo">Val1</a>

function update(event) {
    alert(this);
    event.preventDefault();
}

document.getElementById('foo').addEventListener('click', update);

… and if you don't have a sensible fallback, then use a button, not a link.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • +1, but I did expect you to recommend anonymous functions. addeventlistener('click', function(..){..}) – Mr Lister May 15 '14 at 08:19
  • 1
    I prefer separate function declarations. They are easier to read (since they aren't buried in the middle of another function call) and their name shows up on the stack in debuggers (and while you can have named function expressions, IIRC they leak memory in old-IE). – Quentin May 15 '14 at 08:22