2015年5月3日 星期日

JavaScript and HTML DOM Reference

The references describe the properties and methods of all JavaScript objects, along with examples.

String Number Operators Statements Math Date Array Boolean RegExp Global Conversion

Browser Objects Reference

The references describe the properties and methods of each object, along with examples.

Window Navigator Screen History Location

HTML DOM Reference

The references describe the properties and methods of the HTML DOM, along with examples.

HTML Document HTML Element HTML Attributes HTML Event

HTML Element Objects Reference

The references describe the properties and methods of each HTML object, along with examples.

a abbr address area article aside audio b base bdo blockquote body br button canvas caption cite code col colgroup datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form head header hgroup h1 - h6 hr html i iframe img ins input button input checkbox input color input date input datetime input datetime-local input email input file input hidden input image input month input number input password input radio input range input reset input search input submit input text input time input url input week kbd keygen label legend li link map mark menu menuitem meta meter nav object ol optgroup option output p param pre progress q s samp script section select small source span strong style sub summary sup table td th tr textarea time title track u ul var video


詳細內容可以參考:

JavaScript Window - The Browser Object Model(BOM)

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.


The Browser Object Model (BOM)

There are no official standards for the Browser Object Model (BOM).
說白話一點,這其實是瀏覽器的標準,跟JS沒有關係,只是要理解JS怎麼跟Brower溝通。

Since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to, as methods and properties of the BOM.


The Window Object(瀏覽器物件)

The window object is supported by all browsers. It represents the browser's window.

All global JavaScript objects, functions, and variables automatically become members of the window object.

Global variables are properties of the window object.

Global functions are methods of the window object.

Even the document object (of the HTML DOM) is a property of the window object:
即使是DOM物件,其實也是BOM的子物件(或視為其一個功能屬性。

window.document.getElementById("header");
is the same as:
document.getElementById("header");

多數使用window的函數(功能/指令)時,window這個字通常被省略。


Window Size

Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).

A practical JavaScript solution (covering all browsers):
用或著來判斷使用者的版本,而用不同的指令語法

Example

var w = window.innerWidth
|| document.documentElement.clientWidth  //For 舊版IE 8, 7, 6, 5:語法
|| document.body.clientWidth;     //For 舊版IE 8, 7, 6, 5:語法
ar h = window.innerHeight
|| document.documentElement.clientHeight   //For 舊版IE 8, 7, 6, 5:語法
|| document.body.clientHeight;
  //For 舊版IE 8, 7, 6, 5:語法

The example displays the browser window's height and width: (NOT including toolbars/scrollbars)


Other Window Methods

Some other methods:

    • window.open() - open a new window
    • window.close() - close the current window
    • window.moveTo() -move the current window
    • window.resizeTo() -resize the current window

The window.screen object contains information about the user's screen.


Window Screen (螢幕物件)

The window.screen object can be written without the window prefix(t前輟Window可省)

Properties:

  • screen.width       
  • screen.height
  • screen.availWidth     //minus interface features like the Windows Taskbar
  • screen.availHeight     //minus interface features like the Windows Taskbar
  • screen.colorDepth
  • screen.pixelDepth

The screen.colorDepth property returns the number of bits used to display one color.

All modern computers use 24 bit or 32 bit hardware for color resolution:

  • 24 bits =      16,777,216 different "True Colors"
  • 32 bits = 4,294,967,296 different "Deep Colors"

Older computers used 16 bits: 65,536 different "High Colors" resulution.
Very old computers, and old cell phones used 8 bits: 256 different "VGA colors".

The #rrggbb (rgb) values used in HTML represents "True Colors" (16,777,216 different colors)

Window Screen Pixel Depth

The screen.pixelDepth property returns the pixel depth of the screen.

For modern computers, Color Depth and Pixel Depth are equal.


Window Location (伺服器當地物件)

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

The window.location object can be written without the window prefix.(前輟Window可省)

Some examples:

  • window.location.href            //returns the href (URL) of the current page
    Result is: http://www.w3schools.com/js/js_window_location.asp
  • window.location.hostname   //returns the domain name of the web host
    Result is: www.w3schools.com
  • window.location.pathname  //returns the path and filename of the current page
    Result is:/js/js_window_location.asp
  • window.location.protocol     //returns the web protocol used (http:// or https://)
    Result is:http:  (網頁使用的通訊協定)
  • window.location.assign()      //Method load a new document “ 載入新文件”


Window History (瀏覽器的歷史記錄物件)

The window.history object contains the browsers history.

The window.history object can be written without the window prefix.(前輟Window可省)

To protect the privacy of the users, there are limitations to how JavaScript can access this object.

methods:   //使用這個方法來做上一頁、下一頁的控制

  • history.back() - same as clicking back in the browser
  • history.forward() - same as clicking forward in the browser

History.Back()  and History.Forward()

The history.back()        method loads the previous URL in the history list.
The history forward()   method loads the next URL in the history list.

Example

Create a back button on a page:

<html>
<head>
<script>
function goBack() {
    window.history.back()
}

function goForward() {
    window.history.forward()

}

</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
<input type="button" value="Forward" onclick="goForward()">

</body>
</html>

The output of the code above will be:

The window.navigator object contains information about the visitor's browser.


Window Navigator (瀏覽器版本物件)

The window.navigator object can be written without the window prefix.(前輟Window可省)

Some examples:

  • navigator.appName              //Result is:Netscape
  • navigator.appCodeName       //Result is: Mozilla
  • navigator.cookieEnabled      //true能讀寫cookie;false否則關閉
  • navigator.product                //Result is:Gecko,瀏覽器的引擊版本
  • navigator.appVersion           //Result is:5.0 (Windows)
  • navigator.userAgent            
    //Result is:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
  • navigator.platform                //Result is: Win32
  • navigator.language              //Result is: zh-TW
  • navigator.javaEnabled()       //Result is: false 能否JAVA

Example

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " + navigator.appCodeName;
</script>

Try it Yourself »

Did you know?
IE11, Chrome, Firefox, and Safari return appName "Netscape".
Chrome, Firefox, IE, Safari, and Opera
all return appCodeName "Mozilla".

Warning !!!(嚴重警告)

The information from the navigator object can often be misleading(誤導), and should not be used to detect(檢測) browser versions because:
從Navigator物件得來資料是容易誤導的,不應該用這個方法來檢測瀏覽器的版本。原因如下:

  • Different browsers can use the same name
    //不同瀏覽器可能用相同的名稱
  • The navigator data can be changed by the browser owner
    //資料能被瀏覽器的使用者改變
  • Some browsers misidentify themselves to bypass site tests
    //有些瀏覽器失去視別而己能繞過網站的測試
  • Browsers cannot report new operating systems, released later than the browser
    //不能回報一個新的作業系統、新版本的瀏覽器

JavaScript has three kind of popup boxes: 三種對話框
Alert box, Confirm box, and Prompt box.

  • Alert();               //

  • Confirm();          //OK to return ture ; Cancel

  • Prompt();           //If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.


    Syntax
    window.prompt("sometext","defaultText");
    The window.prompt() method can be written without the window prefix.

Example

var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
    document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}

Try it Yourself »

Line Breaks 在文字框內用 \n 可以斷行
alert("Hello\nHow are you?");


JavaScript Timing Events 定時器事件

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds

Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.


The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

window.setInterval("javascript function", milliseconds);       //(前輟Window可省)The first parameter of setInterval() should be a function.

The second parameter indicates the length of the time-intervals(間隔) between each execution.

Note: There are 1000 milliseconds in one second.

How to Stop the Execution? 停止執行

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

window.clearInterval(intervalVariable)                     //(前輟Window可省)

To be able to use the clearInterval() method, you must use a global variable when creating the interval method:

myVar=setInterval("javascript function", milliseconds);

Then you will be able to stop the execution by calling the clearInterval() method.

Example

Same example as above, but we have added a "Stop time" button:

<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
var myVar = setInterval(function () {myTimer()}, 1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

Try it Yourself »


The setTimeout() Method

Syntax

window.setTimeout("javascript function", milliseconds);       //(前輟Window可省)

The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.

The first parameter of setTimeout() should be a function.

The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

How to Stop the Execution?

Syntax

window.clearTimeout(timeoutVariable)

To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:

myVar=setTimeout("javascript function", milliseconds);

Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.


What are Cookies?

Cookies let you store user information in web pages.

Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his name.

Cookies are saved in name-value pairs like:

username=John Doe

When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.


Create a Cookie with JavaScript (DOM物件)

JavaScript can create, read, and delete cookies with the document.cookie property.
With JavaScript, a cookie can be created like this:

document.cookie="username=John Doe";

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Read a Cookie with JavaScript

With JavaScript, cookies can be read like this:

var x = document.cookie;

document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

 

Change a Cookie with JavaScript

With JavaScript, you can change a cookie the same way as you create it:

document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";              //The old cookie is overwritten.

Delete a Cookie with JavaScript

Deleting a cookie is very simple. Just set the expires parameter to a passed date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Note that you don't have to specify a cookie value when you delete a cookie.

 

The Cookie String

The document.cookie property looks like a normal text string. But it is not.
Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.
If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:

cookie1=value; cookie2=value;

If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.

JavaScript Cookie Example

In the example to follow, we will create a cookie that stores the name of a visitor.

The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie.

The next time the visitor arrives at the same page, he will get a welcome message.

For the example we will create 3 JavaScript functions:

  1. A function to set a cookie value
  2. A function to get a cookie value
  3. A function to check a cookie value

A Function to Set a Cookie

First, we create a function that stores the name of the visitor in a cookie variable:

Example

function setCookie(cname, cvalue, exdays) {
var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

Example explained:

The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.


A Function to Get a Cookie

Then, we create a function that returns the value of a specified cookie:

Example

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
return "";
}

Function explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).

Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).

If the cookie is not found, return "".


A Function to Check a Cookie

Last, we create the function that checks if a cookie is set.

If the cookie is set it will display a greeting.

If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:


All Together Now Example

function setCookie(cname, cvalue, exdays) {
var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}


function getCookie(cname) {           
  //a function to get a cookie
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
return "";
}


function checkCookie() {                   
//a function to check a cookie
var user = getCookie("username");
if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}

Try it Yourself »


詳細內容可以參考:

2015年4月29日 星期三

JavaScript HTML DOM Document

With the HTML DOM, the document object is your web page.


The HTML DOM Document

In the HTML DOM object model, the document object represents(代表/意味著是) your web page. The document object is the owner of all other objects in your web page. If you want to access objects in an HTML page, you always start with accessing the document object.


Finding HTML Elements(取得HTML的元素)

Method Description
document.getElementById() Find an element by element id
用ID代表:唯一
document.getElementsByTagName() Find elements by tag name
用標籤名稱代表,有多個同時選取。
document.getElementsByClassName() Find elements by class name
用群組/類名代表:好幾個元素。


Changing HTML Elements元素的屬性

Method Description
element.innerHTML= Change the inner HTML of an element
<tagName>
inner指的就這個區塊要放入的內容
</tagName>
element.attribute= Change the attribute of an HTML element
<tagName id=”ID名稱” > </tagName>
element.setAttribute(attribute,value) Change the attribute of an HTML element
<tagName id=”ID名稱” > </tagName>

設定A屬性,值Value
element.style.property= Change the style of an HTML element
樣式屬性值:
   

Adding and Deleting Elements 增/刪元素

document.createElement() Create an HTML element
document.removeChild() Remove an HTML element
document.appendChild() Add an HTML element
document.replaceChild()    Replace an HTML element
document.write(text)   Write into the HTML output stream
text幾乎等同整個<html></html>的內容。
因此不寫資料進去,就等於清空網頁的資料。


Adding Events Handlers
一個點擊事件語法,可說是標準/常用到不行的一個「寫法」

Method Description
document.getElementById(id).onclick=function() {
code
}
Adding event handler code to an onclick event
特色1:使用無名函數寫法
特色2:指定元素後直接使用其方法
而方法則對應一個無名函數。

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5. Later, in HTML DOM Level 3, more objects, collections, and properties were added.

Property Description DOM
document.anchors Returns all <a> elements that have a name attribute 1
document.applets Returns all <applet> elements (Deprecated棄用 in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete過時. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1

2015年4月19日 星期日

JavaScript Math Object

  • The Math object allows you to perform mathematical tasks.
  • The Math object includes several mathematical methods.

One common use of the Math object is to create a random number:

Math.random();         // returns a random number 點後.16位 

Math has no constructor. No methods have to create a Math object first.


Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Math.min(0, 150, 30, 20, -8);        // returns –8
Math.max(0, 150, 30, 20, -8);       // returns 150


Math.round()    四捨五入取整數

Math.round() rounds a number to the nearest integer:

Math.round(4.7);            // returns 5
Math.round(4.4);            // returns 4


Math.ceil()        無條件UP取大整數

Math.ceil() rounds a number up to the nearest integer:

Math.ceil(4.4);             // returns  5
Math.ceil(-4.9);             // returns -4

 

Math.floor()       無條件down取小整數

Math.floor() rounds a number down to the nearest integer:

Math.floor(4.7);            // returns 4
Math.floor(-4.7);            // returns -5

 

Math.floor() and Math.random() can be used together to return a random number between 0 and 10:利用這個方法來得到一個0到10的整數

Math.floor(Math.random() * 11); 
// returns a random number between 0 and 10


Math Constants 八個常數值

JavaScript provides 8 mathematical constants that can be accessed with the Math object:

Math.E;                     // returns Euler's number
Math.PI                     // returns PI         圓周率
Math.SQRT2             // returns the square root of 2
Math.SQRT1_2          // returns the square root of 1/2
Math.LN2                  // returns the natural logarithm of 2
Math.LN10                // returns the natural logarithm of 10
Math.LOG2E             // returns base 2 logarithm of E
Math.LOG10E           // returns base 10 logarithm of E

Try it Yourself »


Math Object Methods(真正的數學函數!)

Method

Description

abs(x) Returns the absolute value of x                                       //絶對值
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x)

Returns x, rounded downwards to the nearest integer

log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y                      //次方
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x                                          //開根號
tan(x) Returns the tangent of an angle


Complete Math Reference

For a complete reference, go to our complete Math object reference.

The reference contains descriptions and examples of all Math properties and methods.

JavaScript Events事件

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.


HTML Events

An HTML event can be something the browser does, or something a user does.
網頁的事件一些由瀏覽器觸發,一些由使用者觸動。

Here are some examples of HTML events: (瀏覽器觸發)

  • An HTML web page has finished loading
    //完成下載
  • An HTML input field was changed
    //輸入字段被改變
  • An HTML button was clicked
    點擊按鈕

Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

  • With single quotes: <some-HTML-element some-event='some JavaScript'>
  • With double quotes:<some-HTML-element some-event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a button element:

<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>

In the example above, the JavaScript code changes the content of the element with id="demo".

In the next example, the code changes the content of it's own element (using this.innerHTML):

<button onclick="this.innerHTML=Date()">The time is?</button>

上面這兩個例子,把一推指令、參數、都寫在一起,利用單/雙引號來區別也是可以順利執行。但如再長就很容易出錯。因此通常看到下列的用法:
JavaScript code is often several lines long. It is more common to see event attributes calling functions:

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>


Common HTML Events

Here is a list of some common HTML events:

Event

Description

onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

The list is much longer: W3Schools JavaScript Reference HTML DOM Events.


What can JavaScript Do?

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

  • Things that should be done every time a page loads
  • Things that should be done when the page is closed
  • Action that should be performed when a user clicks a button
  • Content that should be verified when a user inputs data
  • And more ...

Many different methods can be used to let JavaScript work with events:

  • HTML event attributes can execute JavaScript code directly
  • HTML event attributes can call JavaScript functions
  • You can assign your own event handler functions to HTML elements
  • You can prevent events from being sent or being handled
  • And more ...


You will learn a lot more about events and event handlers in the HTML DOM chapters.


JavaScript Scope(變數的範圍)

Scope is the set of variables you have access to.


JavaScript Scope

In JavaScript, objects and functions, are also variables.

In JavaScript, scope is the set of variables, objects, and functions you have access to.

JavaScript has function scope: The scope changes inside functions.


Local JavaScript Variables(內部作用)

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have local scope: They can only be accessed within the function.

// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}

 

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.


Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it. 

var carName = " Volvo";
// code here can use carName
function myFunction() {
// code here can use carName
}


Automatically Global(自動全局要小心!!)

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

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

// code here can use carName
function myFunction() {
    carName = "Volvo";
// code here can use carName
}


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.

Function Arguments

Function arguments (parameters) work as local variables inside functions.


Global Variables in HTML

With JavaScript, the global scope is the complete JavaScript environment.

In HTML, the global scope is the window object: All global variables belong to the window object.全域變數是視窗物件等級,所以就成了視窗的一個屬性

// code here can use window.carName
function myFunction() {
    carName = "Volvo";
}


Did You Know?
Your global variables, or functions, can overwrite window variables or functions.
Anyone, including the window object, can overwrite your global variables or functions.

草稿未完

以前偶爾也想多認識一下程式語言,只是沒這此久。那時費了大半時間還沒認識Function,一時熱情早就被一堆冷變數、資料型態、數學運算、邏輯判斷早就把人弄翻了!

其次,(早期)學習新東西總要用些舉來或實務來增加理解。大部份的例子並沒有錯或不好,但是例子的範圍無形的限制了我們初期生成的觀念,一不小心沒注意到就成了進階時的障礙!那麼來吧!我們也舉例一下囉!

早先例如:變數/變量的宣告及使用,我們可以說宣告一個變量就把一個很多櫃子的拿來使用,櫃子本身在物理條件下,就好像可以看成execl這的資料表的儲存格,真的也是如此的儲存格。所以格子的最外橫向可以做編號、縱向也可做編號,使用變數就像在這些空間的使用。像這樣的例子原則上沒錯吧!也沒什麼大問題。當然問題不在那,而是我們並沒有弄懂這些存儲格的環境。

(至少現在的看法)其實我覺得,運作範圍電腦的內在實務上運作是比較「大」,因而乎略中間過程,這樣反而告成學習的障礙。也就是把乎略的中間過程補回來,思維層級自然就會前進二層,相對的反而更好理解為麼這麼做而不那麼做!

也就是說電腦這小東西,它的運作構架反而可以大到等同一個國家或縣市級的運作程度,或許用最相似的加工區及物流倉儲來說,例如:這個地上有10棟大樓、每棟10樓、每樓10個線、每線100坪?為什麼最後用100坪而不用架子呢?其實是保留一點彈性。因為這是個萬能制造工廠,有些是生產制造區,有些是倉儲區。

因此不管你做什麼這個空間己是固定,這個環境就是電腦的總體資源,硬體上的編號通常是制式的。例如棟、樓及本身的占地面及空間。然啦!我們基本上還是會放上架子或櫃子而架子或櫃子又可放上些格子來分類。所以大體上就是如此!可是會什麼要這廢話多事呢?因為我們必需要明白,電腦運作中我們看不到的架構,這些都是OS的工作。

就如每個倉都使用同樣資料來表來紀錄存放管理資料,就如EXECL這樣的資料表,表中儲存格就可以很好識別、管理及對應到那放這10坪架上放的資料物件!但同樣的一張表如果換到鄰近的其它10坪或隔壁倉去,所對應到內容就會不一樣也不合用!

另一方面這些過程都透過管理中心的個別窗口來處理。所以同樣一個指令在每個位置的結果都是會不同。而現場也同有一組對應用窗口來服務。簡言之,我們下的每一個小小指令或動作,電腦處理都經過很複雜的對應關聯後,再簡化到我們看到。

例如:也我們會說,把左三的東西刪西,就完成了一動作。也沒說那棟、那層、那倉來做,那是因為對應窗口早已設在那相對的位置,所以不要那麼複雜。但如果指令有跨區就會有其它的互動問題,對應的層級不一樣,就有安全機制,這就是「作用域的觀念。」每個工作小組都有對外、對內、及內部管理的機制,就是要記住這件事就對。


物件不是物件?!

這裡順便引入物件這個東西,它不難,因為它是不是東西,基本上他是一個觀念、思法,一種思考的方式。有了它初期很痛苦,後期很強大。這些我想了好久,用我比較熟悉的領域,也許可以解釋。

我們常常用車子、房子來解釋物件是什麼,這很容易理解,但卻造成更多的障礙。為什麼是障礙呢?首先,物件就一個東西來看,有東西就有名稱。而物件本身通常又有很多物件組成,所以又可逐一的剖解好幾層的細部部件,這些還是物件。所以不同層級時,我們處理的內容也會有所不同。我想這樣的解釋都聽過N百遍了,然而依舊無法理理程序語言中的物件是什麼東西。

用個雙性這個特殊字眼也許較容理解它的特別,。

 

因為在寫程序並沒成品,更沒有物品,更該說是設計圖。就像室內設計一樣,在圖面上我們設定了很桌子、椅子、櫃子、燈、明這些物件及用什麼料質、顏色等屬性等等總設計概念圖,有了全局的架構,我們再個別局部去設計各室的空間及細節,也可設計部份元素的創新施工圖。然而些都只是一個前製而己。所以房子是物件、車子是物件、桌子是物件這些一樣也沒有出現。

物件導向我們一般是做單一小物件的細節規劃及製作流程,或是小組織的配置規劃。OP的視窗架構就是物件,而瀏覽器也是一個物件。

而Function用函數這個名稱,我是覺得很不好用,另一個「作用、功用、功能、方法」更能實現他的真正內涵。就是他是為了完成一個動作而設定。也就是連續做些事的的SOP。也就是SOP是不變的,沒有呼叫或調用它,他就不會有結果出來,然不管如何他都只是一個SOP。以物件導向來想就是物件的方法,方法依照SOP去完成一連串工作,最後會有一個結果或品。