Last active
December 3, 2019 22:02
-
-
Save joe-oli/3ca0c6279074c9f923be41f398178936 to your computer and use it in GitHub Desktop.
Random JS notes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//to convert string "true","false" to a boolean | |
var myBool = (mystring === "true"); | |
//because using | |
var myBool = eval(myString) // is evil ! bwahahah | |
//================= | |
//One of the weird behaviour and spec in Javascript is the typeof Array is Object. | |
//You can check if the variable is an array in couple of ways: | |
var isArr = data instanceof Array; | |
var isArr = Array.isArray(data); | |
//But the most reliable way is: | |
isArr = Object.prototype.toString.call(data) == '[object Array]'; | |
//Also you can use jQuery isArray function: | |
var isArr = $.isArray(data); | |
//================= | |
//Check for array: | |
var arr = []; (or) arr = new Array(); | |
var obj = {}; (or) arr = new Object(); | |
arr.constructor.prototype.hasOwnProperty('push') //true | |
obj.constructor.prototype.hasOwnProperty('push') // false | |
//================= | |
//The difference you could see if you had another couple of functions: | |
var h = document.getElementById('a'); | |
h.onclick = doThing_1; | |
h.onclick = doThing_2; | |
h.addEventListener('click', doThing_3); | |
h.addEventListener('click', doThing_4); | |
/* Functions 2, 3 and 4 work, but 1 does not. This is because addEventListener does not overwrite existing event handlers, whereas onclick overrides any existing onclick = fn event handlers. | |
The other significant difference, of course, is that onclick will always work, whereas addEventListener does not work in Internet Explorer before version 9. You can use the analogous attachEvent (which has slightly different syntax) in IE <9. | |
*/ | |
//================= | |
btnSubmit.onclick = MyFunction(); //<== this is WRONG ! you are calling it | |
btnSubmit.onclick = MyFunction; //<== CORRECT WAY: assign function, not call it | |
function MyFunction() { | |
this.disabled = true; | |
//do other stuff | |
} | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= | |
//================= |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment