简体   繁体   中英

Not able to understand the function's behavior

Not able to understand the function's behavior

function Animal() {
    console.log("showing an empty string: " + name);
    console.log("showing not defined: " + other);
}

Animal("Tommy");

Since your function does not take any parameters, than executing

console.log("showing an empty string: " + name);

will result in

showing an empty string:

While executing

console.log("showing not defined: " + other);

will result in error "ReferenceError: other is not defined".

That behavior is because you are using global variables and every window has defined name. By default it's "" (empty string).

So if you open console and write window.name you will get "" and if you write window.other you will get undefined

So every window has a name property mainly accessible by window.name .

So when you are calling that function, the first line is printing

showing an empty string:

Because usually name is an empty variable, and in the second line the variable other is not defined so it is throwing the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM