9

I'm kind of curious why this doesn't work

JavaScript:

function evaluate(){
    console.log(42);
}

HTML:

<a onclick="evaluate()">Click Me!</a>

Is evaluate a reserved keyword somewhere on the html side?

Dan
  • 1,179
  • 2
  • 10
  • 18
  • Interesting. Chrome does not show anything, but Firefox throws `NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments`. This could be because of two different reasons though. – Felix Kling Feb 07 '13 at 16:08
  • That's very strange. I thought it was an alias for eval() but I can call that function using eval. See this http://codepen.io/anon/pen/GFEow. I don't know why I can't call evaluate() directly either. I too think it might be a reserved keyword or something. – praneetloke Feb 07 '13 at 16:19
  • 2
    Possible duplicate of [Is "clear" a reserved word in Javascript?](https://stackoverflow.com/questions/7165570/is-clear-a-reserved-word-in-javascript) – Sebastian Simon Jan 17 '19 at 23:09

3 Answers3

3

"evaluate" is not a reserved keyword, but when it's used in inline event handler, it happens to collide with document's evaluate function(document object is within handler's scope chain before the window object). If you don't want to change your function name, just add window context before it, i.e.

<a onclick="window.evaluate()">Click Me!</a>

Hui Zheng
  • 10,084
  • 2
  • 35
  • 40
3

document.evaluate is needed for parsing XMLs, see the reference in the MDN here.

Uooo
  • 6,204
  • 8
  • 36
  • 63
  • 1
    Another relevant fact is that event handlers are run `with` the document and target node's properties pulled into scope. – Mike Samuel Feb 07 '13 at 16:13
  • 1
    @Mike: Do you have a reference for that? – Felix Kling Feb 07 '13 at 16:15
  • 1
    @FelixKling, 19.1.6 of http://docstore.mik.ua/orelly/webprog/jscript/ch19_01.htm . You can see this at work in `` – Mike Samuel Feb 07 '13 at 16:33
  • @Mike: Thanks! And now that you mention it, I remember that I have seen this before. It's just strange that I cannot find anything in any specification. – Felix Kling Feb 07 '13 at 16:52
  • @FelixKling, Yeah. From that book, "The precise composition of the scope chain has never been standardized and is implementation-dependent. Netscape 6 and Mozilla include all containing objects (even things such as `
    ` tags), while IE 6 sticks to a more minimal set that includes the target element, plus the containing Form object (if any) and the Document object." That level of disagreement is hard to codify after the fact.
    – Mike Samuel Feb 07 '13 at 17:57
3

Evaluate is not a reserved word in JavaScript, document.evaluate is used to evaluate XPath expressions.

You could still name your function evaluate if you used a less obtrusive method of attaching your event handler:

var evaluate = function (){
    console.log(42);
}

document.addEventListener('click', evaluate, false);

Example

Useless Code
  • 12,123
  • 5
  • 35
  • 40