3 ms·
> This is because a property declared in Rect.prototype is not available in Rect itself but only in objects created with new Rect. This isn't really any differ
by nicoburns 4y ago
> This is because a property declared in Rect.prototype is not available in Rect itself but only in objects created with new Rect.
This isn't really any different to other languages. The equivalent for Java would be "(non-static) properties are not available directly on the class but only on instances of that class"
> One tip I've learned when I have to use Javascript: Avoid 'this' whenever possible.
Arrow functions help a lot with this. Their 'this' cannot be overriden and thus is determined by static context only. With regular functions, the rule is that it depends how their called:
- If you call "foo.bar()" then "this" will be "foo".
- But if you do "var baz = foo.bar" then call "baz()", then "this" will be undefined.
- You can always set "this" explicitly by call a function with `.call`. In either "foo.bar.call(quz)" or "baz.call(qux)", "this" will be "qux".
> Oh, and I'm never quite sure when it's a good idea to use 'new'. TFA addresses 'new' a little bit. At least it's not as big a can of worms as 'this'.
Use "new" if and only if you're instantiating a class (whether that's written with the new class syntax or the older prototype syntax). That's it. It's possible to make a constructor work without "new", but it's an extra line of code and is generally considered non-idiomatic.