JS learning notes

本文深入探讨了JavaScript中使用<script>标签的位置、文本字符串断行、变量声明与类型、作用域、变量赋值与生命周期等核心概念。通过具体实例阐述了如何在不同场景下灵活运用JavaScript,并解释了变量赋值于未声明变量时的自动全局作用域特性及变量作用域的生命周期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. use js in HTML, use <script> tag, in <head> or <body> or separate file .js.

2.  You can break up a code line within a text string with a backslash:

var text = "Hello \
World!";
But only inside the string.

3. variables have dynamic types so can be assigned any data type:

var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

var is used to declare one variable, usually without any initialization but for future use, so it's like a container.

any var outside a function is a global variable

4.  The Lifetime of JavaScript Variables
The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.
5. Assigning Values to Undeclared JavaScript Variables
If you assign a value to a variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable.
This statement:

carName = "Volvo";

will declare the variable carName as a global variable , even if it is executed inside a function.

6. Hoisting, default behavior of moving declarations to the top of the current scope. That's why variables are be used before declaration.

7. Self-Invoking Funtions

Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
But it would generate an error if you place a self-invoking function directly in your code like this:
function() {
  code to be executed
}();
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:
Example:

(function () {
  var x = "Hello!!";      // I will invoke myself
})();
8. Functions are Objects
A function defined as the property of an object, is called a method to the object.
A function designed to create new objects, is called an object constructor.

9. Arguments are Passed by Value <=> Objects are Passed by Reference.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值