3 ms·
>>this is only used with the new keyword This so not true. "this" is much wider paradigm in JS.
by sAbakumoff 10y ago
>>this is only used with the new keyword
This so not true. "this" is much wider paradigm in JS.
- z3t4 10y agoIf the new keyword is not used, "this" will point to the global scope. You do not however have to use the new keyword when creating the built in JS objects. {} is new Object(); If you find "this" confusing you can and should avoid using it. JavaScript has many bad parts that some programmers love to use because it makes their code "elegant". It is however possible to write simple and easy to understand code by only using the good parts.
- sAbakumoff 10y ago>>If the new keyword is not used, "this" will point to the global scope This is entirely incorrect information, consider a simple example: function f(){console.log(this.a);} var o={a:"c"} f.call(o) there is no "new" keyword involved, and "this" is not pointing to the global scope and there is a huge amount of other samples which I can show, but I won't. I don't have any problems with understanding "this" in JS. I just firmly believe that this is superb ugly stuff.
- z3t4 10y agoThat is indeed ugly stuff. Thankfully you never have to use f.call(o)
- sAbakumoff 10y agoI bet you never developed anything realistic with JS! The close neighbor of "call" called "apply" is a widely used tool.
- z3t4 10y agoShow me some code and I will refactor it for you.
- sAbakumoff 10y agoJust for fun, why not..Let's take a look at the classic one: Math.hypot.apply(null, [1,1,3,3,4]) Try to refactor without using ES6's "spread" feature(Math.hypot(...[1,1,3,3,4]))
- z3t4 10y agoYou've got an array, and want to "hypotenuse" it. Your code is fine, as it's pretty clear what it does. But for the sake of refactoring: const hypot = arrNum => Math.sqrt(arrNum.reduce((sum,n) => sum + n*n)) hypot([1,1,3,3,4]) Although I would prefer: function hypot(arrNum) { for(var i=0, sum=0; i<arrNum.length; i++) sum += arrNum[i] * arrNum[i]; return Math.sqrt(sum); }
- sAbakumoff 10y agoI don't think it's a good solution because it performs the operation manually instead of calling the built-in Math.hypot method. This is the point - "apply" is a widely used technique, at least it used to be on pre-ES6 times.