Explaining JavaScript and this to people.
-
In all fairness, I think I know why JavaScript can be such a pain to learn. It seems mainly due to piss-poor over complicated explanations online using different terminology than the rest of the world. I just came across another site doing just that. Since someone needs to stand up for JavaScript on CP and right some wrongs I submit to y'all a proper explanation of what was trying to be explained on this site that shall remain nameless. One of the age old confusions with JavaScript has been dealing with the
this
keyword. It's actually pretty simple to understand, provided you find someone who isn't trying to act smart by over complicating crap. If you've ever found yourself wondering why things aren't working the way you'd expect from a different language, well here's the real explanation of it without the hype. Given this code...// in C++, C#, Java, PHP, etc. "this" is seen as an instance of the current object
// same thing in JavaScript, except not everything is an object with itvar fruit = 'Orange';
window.fruit = 'Apple';// unlike other languages, in JavaScript we can invoke this in more ways than one
function explainThis () {
alert(fruit + ' ' + this.fruit);
}// the window object is global by default, so calling explainThis as a function in global scope
// means that when "this" is used in it, it will point to the current object, which is windowexplainThis(); // shows Orange Apple
// if we treat explainThis like an object instead, then the current object in scope of the alert
// becomes the function itself since it's now an object calling the alert instead of a functionvar stuff = new explainThis(); // shows Orange undefined
In JavaScript
this
is simply the context of the current object. Calling something as a function doesn't create a new object in scope, butnew
ing that sucker up does. That's all there is to it. Forget about the kiddies online trying to make this sound more complicated than it is. If this was bugging you, then I hope it helps. I just felt the need to show JavaScript some love since it really is a nifty language. You may now return back to your normal lounging.Jeremy Falcon
And Perl?
-
And Perl?
Beats me. I haven't touched Perl in a loooong time. You're on your own. :laugh:
Jeremy Falcon
-
I think Javascript is such a PITA to learn because: 1) my bias to what I expect. I experience this with Python as well. Anything from differently named functions for string manipulation to the whole abortion called the DOM. 2) too many strings.
$("#foo")
3) too many things hard to type. Shift-$. Shift paren. Shift quote. Shift pound. Unshift. The rest of the identifier. Shift quote. Shift close parent. Unshift. Dot. etc... 4) string function name or function or property?$("#foo").val();
vs.event.args.innerText
vs. (jqxWidgets example)$("#menu").jqxMenu("close");
5) Standards hell: For example, single quote or double quote:$("#menu").jqxMenu('close');
6) Insane (or is that inane) document traversal:var parentItemText = $($($("#projectTree1").jqxTree('getSelectedItem').parentElement).children("div")[1]).text();
7) Closure madness (ok, once you get familiar with the syntax, yeah, it makes sense):myLayout.registerComponent('Output', function (container, componentState) {
container.getElement().html($("#buildOutputContainer").html().replace("buildOutput", "buildOutput1"));
container.on("resize", (function (c) {
var ct = c;
return function () {
$("#buildOutput1").jqxTextArea({ width: ct.width + "px", height: ct.height + "px" });
};
})(container));
});- div hell. OK, not related to Javascript 9) framework hell. Too many, too complicated, too annoying, too idiocentric. 10) Untestable. Except by trying it manually. Yeah, I've tried a variety of test frameworks, even tried writing my own. They all suck. Should I go on? These are all barriers to: 1) Really grocking Javascript. For example, I just discovered this cool way to eliminate the stupidity of all these strings for acquiring elements by ID or "class" name:
id = new Proxy({},
{
get: function (target, prop) {
return function () { return $("#" + prop); };
}
});Usage:
id.menubar().jqxMenu({ width: 600, height: 30 });
instead of this crap:$("#menubar").jqxMenu({ width: 600, height: 30 });
Should I do that or not? Performance penalty vs. readability? Is it more readable? Will it confuse someone who has to maintain the code. Versus, say, a server-side replacement like!menubar.jqxMenu...
Yet again another kludge that requires that you know something totally outside of pure Javascript to under -
I think Javascript is such a PITA to learn because: 1) my bias to what I expect. I experience this with Python as well. Anything from differently named functions for string manipulation to the whole abortion called the DOM. 2) too many strings.
$("#foo")
3) too many things hard to type. Shift-$. Shift paren. Shift quote. Shift pound. Unshift. The rest of the identifier. Shift quote. Shift close parent. Unshift. Dot. etc... 4) string function name or function or property?$("#foo").val();
vs.event.args.innerText
vs. (jqxWidgets example)$("#menu").jqxMenu("close");
5) Standards hell: For example, single quote or double quote:$("#menu").jqxMenu('close');
6) Insane (or is that inane) document traversal:var parentItemText = $($($("#projectTree1").jqxTree('getSelectedItem').parentElement).children("div")[1]).text();
7) Closure madness (ok, once you get familiar with the syntax, yeah, it makes sense):myLayout.registerComponent('Output', function (container, componentState) {
container.getElement().html($("#buildOutputContainer").html().replace("buildOutput", "buildOutput1"));
container.on("resize", (function (c) {
var ct = c;
return function () {
$("#buildOutput1").jqxTextArea({ width: ct.width + "px", height: ct.height + "px" });
};
})(container));
});- div hell. OK, not related to Javascript 9) framework hell. Too many, too complicated, too annoying, too idiocentric. 10) Untestable. Except by trying it manually. Yeah, I've tried a variety of test frameworks, even tried writing my own. They all suck. Should I go on? These are all barriers to: 1) Really grocking Javascript. For example, I just discovered this cool way to eliminate the stupidity of all these strings for acquiring elements by ID or "class" name:
id = new Proxy({},
{
get: function (target, prop) {
return function () { return $("#" + prop); };
}
});Usage:
id.menubar().jqxMenu({ width: 600, height: 30 });
instead of this crap:$("#menubar").jqxMenu({ width: 600, height: 30 });
Should I do that or not? Performance penalty vs. readability? Is it more readable? Will it confuse someone who has to maintain the code. Versus, say, a server-side replacement like!menubar.jqxMenu...
Yet again another kludge that requires that you know something totally outside of pure Javascript to underMarc, that's a lot of stuff to go over man. At lot of these points are mainly due to design concerns and just being old and resistant to change. ;P Forgive me, but I'll have to skim over some of this stuff, but will address some points
Marc Clifton wrote:
- my bias to what I expect. I experience this with Python as well. Anything from differently named functions for string manipulation to the whole abortion called the DOM.
It's an object representation of what's displayed. I'm not sure how it's an abortion. About the only thing I can see with that is old skool compatiblity issues. You can blame Microsoft and Mozilla for that. They didn't give two flips about each other. But those days are gone for the most part. Life is better.
Marc Clifton wrote:
- too many strings.
$("#foo")
Marc, we're professionals man. Come on.
Marc Clifton wrote:
- Standards hell: For example, single quote or double quote:
$("#menu").jqxMenu('close');
Most web languages support both. Can't blame JavaScript for that.
Marc Clifton wrote:
var parentItemText = $($($("#projectTree1").jqxTree('getSelectedItem').parentElement).children("div")[1]).text();
Clearly, you're looking at code written by a 5 year old that doesn't know anything about CSS selectors or jQuery.
Marc Clifton wrote:
Should I do that or not? Performance penalty vs. readability? Is it more readable? Will it confuse someone who has to maintain the code.
Unless you're willing to refactor everything, then yeah that's nifty. The problem here is the design. Back in the olden days, JavaScript was tightly coupled with the DOM. Those days have changed man. I'm not saying it doesn't exist, but it's not nearly has bad as the olden days. Dealing with JScript or VBScript as no different though. It's just the way web dev was for years, and it's not really that much different in concept than XAML and people using ViewModels poorly.
Marc Clifton wrote:
Why do I do this? So I can have a nice function named "getProjectId" that tells me exactly what is going on, without passing in a string and without writing the abortion that looks like this:
Oh Marc, you're having fun with this aren't you? :rolleyes:
-
Marc Clifton wrote:
I hope you enjoyed this post!
Enjoyed it? Unsure, still reeling. But it has helped me narrow down what I might learn next: It 'aint javascript.
Marc's just old. Don't listen to him. :)
Jeremy Falcon
-
I think Javascript is such a PITA to learn because: 1) my bias to what I expect. I experience this with Python as well. Anything from differently named functions for string manipulation to the whole abortion called the DOM. 2) too many strings.
$("#foo")
3) too many things hard to type. Shift-$. Shift paren. Shift quote. Shift pound. Unshift. The rest of the identifier. Shift quote. Shift close parent. Unshift. Dot. etc... 4) string function name or function or property?$("#foo").val();
vs.event.args.innerText
vs. (jqxWidgets example)$("#menu").jqxMenu("close");
5) Standards hell: For example, single quote or double quote:$("#menu").jqxMenu('close');
6) Insane (or is that inane) document traversal:var parentItemText = $($($("#projectTree1").jqxTree('getSelectedItem').parentElement).children("div")[1]).text();
7) Closure madness (ok, once you get familiar with the syntax, yeah, it makes sense):myLayout.registerComponent('Output', function (container, componentState) {
container.getElement().html($("#buildOutputContainer").html().replace("buildOutput", "buildOutput1"));
container.on("resize", (function (c) {
var ct = c;
return function () {
$("#buildOutput1").jqxTextArea({ width: ct.width + "px", height: ct.height + "px" });
};
})(container));
});- div hell. OK, not related to Javascript 9) framework hell. Too many, too complicated, too annoying, too idiocentric. 10) Untestable. Except by trying it manually. Yeah, I've tried a variety of test frameworks, even tried writing my own. They all suck. Should I go on? These are all barriers to: 1) Really grocking Javascript. For example, I just discovered this cool way to eliminate the stupidity of all these strings for acquiring elements by ID or "class" name:
id = new Proxy({},
{
get: function (target, prop) {
return function () { return $("#" + prop); };
}
});Usage:
id.menubar().jqxMenu({ width: 600, height: 30 });
instead of this crap:$("#menubar").jqxMenu({ width: 600, height: 30 });
Should I do that or not? Performance penalty vs. readability? Is it more readable? Will it confuse someone who has to maintain the code. Versus, say, a server-side replacement like!menubar.jqxMenu...
Yet again another kludge that requires that you know something totally outside of pure Javascript to underJust to give you an idea of where the web is headed, here is some ES2015 code...
import React from 'react';
import {Link} from 'react-router';class Layout extends React.Component {
// this requires that the class fields and static properties plug-in is enabled
static propTypes = {
children: PropTypes.object.isRequired
};render() {
// returned JSX must be within parenthesis
return (
// class is a reserved word in JavaScript so we use className insteadheader here and all
{this.props.children} );
}
};export default Layout;
Btw, that's not HTML inside the render method. It's just syntactic sugar to look like it. It gets transpiled down to JavaScript. But the only strings you'll see here are in the imports (which isn't much different than C/C++ includes) and the properties that will be spit out to the browser such as "container-fluid". Well, there is the literal there too, but none of the
$($($($('omg'))))
stuff. :laugh: Now, I'm not saying everything is perfect with the web. But new-skool web development (especially as WASM gets more popular) is nothing like old-skool web development.Jeremy Falcon
-
Marc's just old. Don't listen to him. :)
Jeremy Falcon
-
Jeremy Falcon wrote:
Marc's just old. Don't listen to him. :)
We call it wisdom. (I suffer the same affliction.)
Oh snap. :thumbsup:
Jeremy Falcon
-
In all fairness, I think I know why JavaScript can be such a pain to learn. It seems mainly due to piss-poor over complicated explanations online using different terminology than the rest of the world. I just came across another site doing just that. Since someone needs to stand up for JavaScript on CP and right some wrongs I submit to y'all a proper explanation of what was trying to be explained on this site that shall remain nameless. One of the age old confusions with JavaScript has been dealing with the
this
keyword. It's actually pretty simple to understand, provided you find someone who isn't trying to act smart by over complicating crap. If you've ever found yourself wondering why things aren't working the way you'd expect from a different language, well here's the real explanation of it without the hype. Given this code...// in C++, C#, Java, PHP, etc. "this" is seen as an instance of the current object
// same thing in JavaScript, except not everything is an object with itvar fruit = 'Orange';
window.fruit = 'Apple';// unlike other languages, in JavaScript we can invoke this in more ways than one
function explainThis () {
alert(fruit + ' ' + this.fruit);
}// the window object is global by default, so calling explainThis as a function in global scope
// means that when "this" is used in it, it will point to the current object, which is windowexplainThis(); // shows Orange Apple
// if we treat explainThis like an object instead, then the current object in scope of the alert
// becomes the function itself since it's now an object calling the alert instead of a functionvar stuff = new explainThis(); // shows Orange undefined
In JavaScript
this
is simply the context of the current object. Calling something as a function doesn't create a new object in scope, butnew
ing that sucker up does. That's all there is to it. Forget about the kiddies online trying to make this sound more complicated than it is. If this was bugging you, then I hope it helps. I just felt the need to show JavaScript some love since it really is a nifty language. You may now return back to your normal lounging.Jeremy Falcon
-
Just to give you an idea of where the web is headed, here is some ES2015 code...
import React from 'react';
import {Link} from 'react-router';class Layout extends React.Component {
// this requires that the class fields and static properties plug-in is enabled
static propTypes = {
children: PropTypes.object.isRequired
};render() {
// returned JSX must be within parenthesis
return (
// class is a reserved word in JavaScript so we use className insteadheader here and all
{this.props.children} );
}
};export default Layout;
Btw, that's not HTML inside the render method. It's just syntactic sugar to look like it. It gets transpiled down to JavaScript. But the only strings you'll see here are in the imports (which isn't much different than C/C++ includes) and the properties that will be spit out to the browser such as "container-fluid". Well, there is the literal there too, but none of the
$($($($('omg'))))
stuff. :laugh: Now, I'm not saying everything is perfect with the web. But new-skool web development (especially as WASM gets more popular) is nothing like old-skool web development.Jeremy Falcon
(and now I feel guilty about not finishing up the React colourising definitions...)
cheers Chris Maunder
-
Chris Maunder wrote:
Now explain closures and you'll have everyone halfway there.
You'll hear 40 million different definitions online about that. And most of them try to sound smart, but put simply it's a function within a function. People will try to tack on crap with scoping etc. to that definition when "explaining" it, but that's irrelevant to the core concept of it IMO.
Chris Maunder wrote:
And of course the obligatory WAT video whenever Javascript weirdness is raised.
Ok, that dude is hilarious. I have no idea why the object stuff in JavaScript turned out the way it did, but I can at least explain the
'wat' + 1
thing. The plus sign is used for string concatenation and arithmetic. The minus sign isn't. So in the former example, the interpreter assumes you're trying to concatenate using the most compatible types between the two operands, which is usually a string. The minus sign only only used for arithmetic and so it's NaN.Jeremy Falcon
-
(and now I feel guilty about not finishing up the React colourising definitions...)
cheers Chris Maunder
Muwahahahahahah. Then my work here is done.
Jeremy Falcon
-
Chris Maunder wrote:
Now explain closures and you'll have everyone halfway there.
You'll hear 40 million different definitions online about that. And most of them try to sound smart, but put simply it's a function within a function. People will try to tack on crap with scoping etc. to that definition when "explaining" it, but that's irrelevant to the core concept of it IMO.
Chris Maunder wrote:
And of course the obligatory WAT video whenever Javascript weirdness is raised.
Ok, that dude is hilarious. I have no idea why the object stuff in JavaScript turned out the way it did, but I can at least explain the
'wat' + 1
thing. The plus sign is used for string concatenation and arithmetic. The minus sign isn't. So in the former example, the interpreter assumes you're trying to concatenate using the most compatible types between the two operands, which is usually a string. The minus sign only only used for arithmetic and so it's NaN.Jeremy Falcon
Now it's 40 000 001
Wrong is evil and must be defeated. - Jeff Ello
-
In all fairness, I think I know why JavaScript can be such a pain to learn. It seems mainly due to piss-poor over complicated explanations online using different terminology than the rest of the world. I just came across another site doing just that. Since someone needs to stand up for JavaScript on CP and right some wrongs I submit to y'all a proper explanation of what was trying to be explained on this site that shall remain nameless. One of the age old confusions with JavaScript has been dealing with the
this
keyword. It's actually pretty simple to understand, provided you find someone who isn't trying to act smart by over complicating crap. If you've ever found yourself wondering why things aren't working the way you'd expect from a different language, well here's the real explanation of it without the hype. Given this code...// in C++, C#, Java, PHP, etc. "this" is seen as an instance of the current object
// same thing in JavaScript, except not everything is an object with itvar fruit = 'Orange';
window.fruit = 'Apple';// unlike other languages, in JavaScript we can invoke this in more ways than one
function explainThis () {
alert(fruit + ' ' + this.fruit);
}// the window object is global by default, so calling explainThis as a function in global scope
// means that when "this" is used in it, it will point to the current object, which is windowexplainThis(); // shows Orange Apple
// if we treat explainThis like an object instead, then the current object in scope of the alert
// becomes the function itself since it's now an object calling the alert instead of a functionvar stuff = new explainThis(); // shows Orange undefined
In JavaScript
this
is simply the context of the current object. Calling something as a function doesn't create a new object in scope, butnew
ing that sucker up does. That's all there is to it. Forget about the kiddies online trying to make this sound more complicated than it is. If this was bugging you, then I hope it helps. I just felt the need to show JavaScript some love since it really is a nifty language. You may now return back to your normal lounging.Jeremy Falcon
-
Javascript has become a powerful language. With this comes responsibility :~
Press F1 for help or google it. Greetings from Germany
Wisdom you speak. Wisdom you speak...
Jeremy Falcon
-
Now it's 40 000 001
Wrong is evil and must be defeated. - Jeff Ello
:-D
Jeremy Falcon
-
I think Javascript is such a PITA to learn because: 1) my bias to what I expect. I experience this with Python as well. Anything from differently named functions for string manipulation to the whole abortion called the DOM. 2) too many strings.
$("#foo")
3) too many things hard to type. Shift-$. Shift paren. Shift quote. Shift pound. Unshift. The rest of the identifier. Shift quote. Shift close parent. Unshift. Dot. etc... 4) string function name or function or property?$("#foo").val();
vs.event.args.innerText
vs. (jqxWidgets example)$("#menu").jqxMenu("close");
5) Standards hell: For example, single quote or double quote:$("#menu").jqxMenu('close');
6) Insane (or is that inane) document traversal:var parentItemText = $($($("#projectTree1").jqxTree('getSelectedItem').parentElement).children("div")[1]).text();
7) Closure madness (ok, once you get familiar with the syntax, yeah, it makes sense):myLayout.registerComponent('Output', function (container, componentState) {
container.getElement().html($("#buildOutputContainer").html().replace("buildOutput", "buildOutput1"));
container.on("resize", (function (c) {
var ct = c;
return function () {
$("#buildOutput1").jqxTextArea({ width: ct.width + "px", height: ct.height + "px" });
};
})(container));
});- div hell. OK, not related to Javascript 9) framework hell. Too many, too complicated, too annoying, too idiocentric. 10) Untestable. Except by trying it manually. Yeah, I've tried a variety of test frameworks, even tried writing my own. They all suck. Should I go on? These are all barriers to: 1) Really grocking Javascript. For example, I just discovered this cool way to eliminate the stupidity of all these strings for acquiring elements by ID or "class" name:
id = new Proxy({},
{
get: function (target, prop) {
return function () { return $("#" + prop); };
}
});Usage:
id.menubar().jqxMenu({ width: 600, height: 30 });
instead of this crap:$("#menubar").jqxMenu({ width: 600, height: 30 });
Should I do that or not? Performance penalty vs. readability? Is it more readable? Will it confuse someone who has to maintain the code. Versus, say, a server-side replacement like!menubar.jqxMenu...
Yet again another kludge that requires that you know something totally outside of pure Javascript to under -
In all fairness, I think I know why JavaScript can be such a pain to learn. It seems mainly due to piss-poor over complicated explanations online using different terminology than the rest of the world. I just came across another site doing just that. Since someone needs to stand up for JavaScript on CP and right some wrongs I submit to y'all a proper explanation of what was trying to be explained on this site that shall remain nameless. One of the age old confusions with JavaScript has been dealing with the
this
keyword. It's actually pretty simple to understand, provided you find someone who isn't trying to act smart by over complicating crap. If you've ever found yourself wondering why things aren't working the way you'd expect from a different language, well here's the real explanation of it without the hype. Given this code...// in C++, C#, Java, PHP, etc. "this" is seen as an instance of the current object
// same thing in JavaScript, except not everything is an object with itvar fruit = 'Orange';
window.fruit = 'Apple';// unlike other languages, in JavaScript we can invoke this in more ways than one
function explainThis () {
alert(fruit + ' ' + this.fruit);
}// the window object is global by default, so calling explainThis as a function in global scope
// means that when "this" is used in it, it will point to the current object, which is windowexplainThis(); // shows Orange Apple
// if we treat explainThis like an object instead, then the current object in scope of the alert
// becomes the function itself since it's now an object calling the alert instead of a functionvar stuff = new explainThis(); // shows Orange undefined
In JavaScript
this
is simply the context of the current object. Calling something as a function doesn't create a new object in scope, butnew
ing that sucker up does. That's all there is to it. Forget about the kiddies online trying to make this sound more complicated than it is. If this was bugging you, then I hope it helps. I just felt the need to show JavaScript some love since it really is a nifty language. You may now return back to your normal lounging.Jeremy Falcon
I am currently writing a road traffic simulator in javascript and both at work and in this project the one thing that makes javascript difficult is scope. Basically the manner in which scope is implemented javascript makes it that much more difficult than it needs to be. That said I have found that programming in javascritpt has made me a better developer because there are so many ways you can do things badly in javascript.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
-
In all fairness, I think I know why JavaScript can be such a pain to learn. It seems mainly due to piss-poor over complicated explanations online using different terminology than the rest of the world. I just came across another site doing just that. Since someone needs to stand up for JavaScript on CP and right some wrongs I submit to y'all a proper explanation of what was trying to be explained on this site that shall remain nameless. One of the age old confusions with JavaScript has been dealing with the
this
keyword. It's actually pretty simple to understand, provided you find someone who isn't trying to act smart by over complicating crap. If you've ever found yourself wondering why things aren't working the way you'd expect from a different language, well here's the real explanation of it without the hype. Given this code...// in C++, C#, Java, PHP, etc. "this" is seen as an instance of the current object
// same thing in JavaScript, except not everything is an object with itvar fruit = 'Orange';
window.fruit = 'Apple';// unlike other languages, in JavaScript we can invoke this in more ways than one
function explainThis () {
alert(fruit + ' ' + this.fruit);
}// the window object is global by default, so calling explainThis as a function in global scope
// means that when "this" is used in it, it will point to the current object, which is windowexplainThis(); // shows Orange Apple
// if we treat explainThis like an object instead, then the current object in scope of the alert
// becomes the function itself since it's now an object calling the alert instead of a functionvar stuff = new explainThis(); // shows Orange undefined
In JavaScript
this
is simply the context of the current object. Calling something as a function doesn't create a new object in scope, butnew
ing that sucker up does. That's all there is to it. Forget about the kiddies online trying to make this sound more complicated than it is. If this was bugging you, then I hope it helps. I just felt the need to show JavaScript some love since it really is a nifty language. You may now return back to your normal lounging.Jeremy Falcon
-
I got a chuckle out of that as well.
"There are three kinds of lies: lies, damned lies and statistics." - Benjamin Disraeli