Hacker News new | ask | show | jobs
by TazeTSchnitzel 4209 days ago
This post is way, way too long. Rather than explaining the simple principles that lead to the behaviour JS's this has, the post just lists example after example.

JS 'this' is a variable defined within a function. If that function is called as if it were a method, e.g. obj.somefunc(), 'this' is that object, obj. Otherwise, 'this' is the global object (quirks mode) or undefined (strict mode). If a function is called with the new keyword, 'this' is set to a new object whose prototype is set to the property named 'prototype' on the function.

The prototype of an object is a fallback: if you try to read a property on an object and it lacks such a property, it'll grab it from its prototype (or its prototype's prototype etc.) if it has it. If you write to or create a property on an object, it always goes on the object and won't touch the prototype.

The weird behaviour for DOM events isn't weird. It just calls the onclick method as a method.

1 comments

Your explanation is way simpler to understand than the lengthy original article.

Maybe one addition: the value of 'this' inside a function FN can also be set by a caller of FN by using the form FN.call(this-ptr-value, arg1, arg2, ..) instead of FN(arg1, arg2, ..)