學習筆記:Java大數據培訓學校全套教程-JavaScript基礎(20)

立即學習:https://edu.csdn.net/course/play/9840/209168?utm_source=blogtoedu

作者的示例代碼在如下地址: http://www.mark-to-win.com/Javascript/js1_web.html

本文內容是根據講師馬克的視頻筆記,參考作者的代碼,由於作者的代碼太隨性了,且是txt的,看着效果實在難受,遂經將其整理收錄至本文。

第一章 JS 基礎

 

第零節 前言

 

第一節 JS 基礎

1.基礎知識

1) Helloworld

例 1.1

<html>
<head>
    <!-- 如果你用notepad建立一個txt之後你再改爲html,一定在保存時,要保存爲utf-8或unicode格式,
或者你也可以用myeclipse html designer編輯,這樣你看的文本是有顏色的,如果覺得字體小,
可以在myeclipse html designer下面的窗口裏右擊鼠標,/preferences/general/editor/text editor.
注意在texteditor窗口裏面的右邊最下面,有一行不起眼你的小字,color and font,你可以設置。-->
</head>
<script type="text/javascript">
    var a ;
    /*before you set value, a' type can not be defined.*/
    document.writeln("Before set value, type of 'a' is " + typeof(a) + ";<br>");
    a = true;
    document.writeln("After set a boolean type value, tpye of 'a' is " + typeof(a) + ";<br>");
    /*下面的console.log只有安裝了firebug的firebox不報錯*/
    console.log("This is the a message when show value of %s ;", a);
    document.writeln("After set a boolean type value, value of 'a' is " + a + ";");
</script>
</html>

輸出結果:

Before set value, type of 'a' is undefined;
After set a boolean type value, type of 'a' is boolean;
After set a boolean type value, value of 'a' is true; 

 控制檯顯示如下

2)火狐的firebug如何單步調試程序

3)html當中如何引用js文件

注:如果需要javascript工程師和html美工各幹各的工作,需要分開寫文件。

例 1.2

<html>
<head>
    <script src="Hello.js"></script>
    <title></title>
</head>
<body>
</body>
</html>

Hello.js 文件內容如下:(如果你用notepad建立一個txt之後你再改爲js,一定在存時,要存成utf-8或unicode格式):

var a ;
/*before you set value, a' type can not be defined.*/
document.writeln(typeof(a) + "<br>他們");
a = true;
document.writeln(typeof(a) + "<br>");
/*下面的console.log只有安裝了firebug的firebox不報錯*/
console.log("This is the 1 message 馬克-to-win write in %s", a);
document.writeln(a);

2.簡單語法:

例 2.1

<html>
<head>
</head>
<body>
<script type="text/javascript">
    var i = 0;
    do
    {
        i += 1;
        window.document.write("i=" + i + "<br>");
    }
    while (i < 3)
</script>我們
</body>
</html>

輸出結果:

i=1
i=2
i=3
我們 

例 2.2

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <script type="text/javascript">
        var i = 5;
        while (i > 0) {
            window.document.write("value of i is : " + i + "<br>");
            i--;
        }
    </script>
</head>
<body>

</body>
</html>

輸出結果:

value of i is : 5
value of i is : 4
value of i is : 3
value of i is : 2
value of i is : 1

例 2.3(自動轉化,比如3<"4")

<html>
<head>
    <script type="text/javascript">
        result = 0;
        function qiuhe()
        {
            var num = window.document.getelementbyid("num").value;
            /*the following typeof(num) is a string. can automatically convert string to number.*/
            alert("typeof(num) is "+typeof(num));
            for (var i = 1; i <= num; i++)
            {
                result = result+i;
            }
            window.document.getelementbyid("result").value = result;
        }
    </script>
</head>
<body>
從1累加到
<input type="text" id="num" size="5">之和是<br>
<input type="text" id="result">
<input type="submit" onclick="qiuhe();" value="cal">
</body>
</html>

輸出結果:

當輸入50時

例 2.4

注:javascript中,當作爲字符串時,單引號和雙引號是通用的,都行。

如下面的例子:如二者同時用,才需要配對。比如: <body οnlοad='a("a","b","c")'>

<html>
<head>
    <script type="text/javascript">
        var sex = 'female';
        if (sex == "female")
            this.document.writeln("小姐");
        else
            this.document.writeln('先生');
    </script>
</head>
<body>
</body>
</html>

輸出結果:

小姐

例 2.5

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">
        document.write("hello world <br>");
        with (document) {
            write("hello world with with1<br>");
            write("hello world with with2<br>");
        }
    </script>
</head>
<body>
</body>
</html>

輸出結果:

hello world
hello world with with1
hello world with with2

例 2.6

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <script language="javascript">
        var a = 12,b = 34,c = 56;
        c = ++a + b;
        //a值再加1爲13,再加b34,c值爲47
        document.writeln("c=" + c + "<br>");
        document.writeln("b=" + b + "<br>");
        document.writeln("a=" + a + "<br>");
    </script>
    <title></title>
</head>
<body>
</body>
</html>

輸出結果:

c=47
b=34
a=13

例 2.7(Document.write語法)

<html>
<head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

<title>
</title>
</head>
<body>
this content is before document.write <br>
<script type="text/javascript">

    document.write("<hr size=2 color='orange' width=50% align=left>");
    for (var i = 5; i > 0; i--)
    {
        if (i == 3) continue;
        document.write("i=" + i + "<br>");
    }

</script>
<br>this content is after document.write <br>
</body>
</html>

輸出結果:

 

例 2.8(prompt)

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <script>
        /*JavaScript syntax: - myResult = myWindow.prompt(aString, aDefaultValue)
        - myResult = prompt(aString, aDefaultValue)
        Argument list: aDefaultValue An initial content for the text box
        aString Some text to explain what to enter
        */
        var yourgender = prompt("你的性別是:\n男生請按11,女生請按22", "22");

        switch (yourgender) {
            case "11"    : document.writeln("你好!"); break;
            case "22"    : document.writeln("你好!woman"); break;
            default    : document.writeln("重按!");
        }

    </script>
</head>
<body>
</body>
</html>

輸出結果:

默認的輸入框是22

若是輸入11則

如是輸入 其他數字,如123,則

3.其他高級話題:

1)類型轉換,typeof的用法

例 3.1.1

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    </head>
    <body>
        <script language="javascript">
            <!--
            /*
            Cast operator (Definition)  refer to 過去的網站www.favo.com
            A way of converting data types.
            Primitive values can be converted from one to another or rendered as objects by using object constructors to convert the values.
                                    
            Boolean                                      
            Number                                       
            String                                       

            Number() (Function)  馬克-to-win: actually Number() is the method of Global object.
            A Number type convertor.

            Property/method value type: Number primitive
            JavaScript syntax: - Number()
            - Number(aValue)
            Argument list: aValue A value to be converted to a number.

            When the Number() constructor is called as a function, it will perform a type conversion.
            The following values are yielded as a result of calling Number() as a function:

            Value                            Result
            Number                            No conversion, the input value is returned unchanged.
            Non numeric string                NaN

            window.Number("23");在favo中查不出來, 但Idea中可以打點打出來。
            */
            -->
            
            var a = 9;
            /*下句話如果放在ie8中執行, 必須打開debug工具*/
            console.log(typeof(a));
            document.writeln("typeof(a) is : " + typeof(a) + "<br>");
            var as = String(a);
            //string是global的方法
            document.writeln("typeof(as) is : " + typeof(as) + "<br>");
            var x = window.Number("23");
            document.writeln("typeof(x) is : " + typeof(x) + "<br>");
            var age2 = Number("56");
            document.writeln("typeof(age2) is : " + typeof(age2) + "<br>");
            var age3 = new Number(56);
            document.writeln("typeof(age3) is : " + typeof(age3) + "<br>");
            var y = Number("23xyz");
            document.writeln("x=" + x + ", y=" + y + ", typeof(y) is : " + typeof(y) + "<br>");

        </script>
    </body>
</html>

輸出結果:

例 3.1.2

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    </head>
    
    <script>
        /*javascript support type automatic conversion.the same value is equal */
        document.writeln(6 == "6");
        document.writeln("<br>");
        /*the following requires that value and type should be the same.*/
        document.writeln(6 === "6");
        document.writeln("<br>");
            /*When the Global object is created, it always has at least the following properties:
           Object object       Function object       Array object       String object
           Boolean object       Number object       Date object       Math object
           Value properties
       */
        var obj1 = new window.Object();
        var obj2 = new Object();
        /*Object references must refer to the same object instance.otherwise return false.*/
        document.writeln(obj1 == obj2);
        document.writeln("<br>");
        document.writeln(typeof(obj1) === typeof(obj2));
    </script>
    
    <body>
    </body>
</html>

輸出結果:

true
false
false
true 

例 3.1.3(null和undefined的==和===的比較)

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    </head>
    
    <script>    
        /* if a value is not set, its typeof is undefined, its value is undefined, if a value= null, 
        its typeof is object, its value is null,but when you use == to test, they are the same, but when to
        use === to test, they are not the same,== means as long as value is the same, 
        ok, but === means type also must be equal. */
        //聲明變量x
        var x;
        var z1 = "d";
        var y = null;

        //document.writeln("z1 is"+z1);
        /*if you cancel commenting out the following statement, it will give the blank page, which means it has error.*/
        //document.writeln(zyx);
        document.writeln("x is : " + x + " <br>");
        document.writeln("typeof(x) is : " + typeof(x) + "<br>");
        document.writeln("y is : " + y + "<br>");
        document.writeln("typeof(y) is : " + typeof(y) + "<br>");
        var z = undefined;
        //document.writeln("z is : " + z + "<br>");
        document.writeln("typeof(z) is : " + typeof(z) + "<br>");
        if (y == undefined)
        {
            document.writeln('null and undefined is interchangable <br>');
        }
        if (z1 != null)
        {
            document.writeln('z1 != null');
            document.writeln('<br>');
        }
        if (y === undefined)
        {
            document.writeln('null and undefined is exactly the same <br>');
        }
        if (x == undefined)
        {
            document.writeln('聲明變量後默認值爲 undefined <br>');
        }

        if (x === undefined)
        {
            document.writeln('聲明變量後默認值爲 exactly the same as undefined <br>');
        }

        if (x == null)
        {
            document.writeln('聲明變量後默認值爲 null <br>');
        }

        if (x === null)
        {
            document.writeln('馬克-to-win:聲明變量後默認值爲 exactly the same as null, note that null\' s typeof is Object. <br>');
        }

        if (x == y)
        {
            document.writeln("x等於y <br>");
        }
        if (x === z)
        {
            document.writeln("x三等於z <br>");
        }
    </script>

    <body>
    </body>
</html>

輸出結果:

x is : undefined
typeof(x) is : undefined
y is : null
typeof(y) is : object
typeof(z) is : undefined
null and undefined is interchangable
z1 != null
聲明變量後默認值爲 undefined
聲明變量後默認值爲 exactly the same as undefined
聲明變量後默認值爲 null
x等於y
x三等於z 

2)局部變量和全局變量

注:瀏覽器裏面 window 就是 global,通常可以省。nodejs 裏沒有 window,但是有個叫 global 的。

例 3.2.1

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
    <script>
        /* 馬克-to-win:有var無var, 在function外是一樣的,都是全局的,在function裏面時,var是局部的,而無var時是代表全局的*/  
        var testVar = "全局變量";
        document.writeln("window.testVar is " + window.testVar + " | " + testVar + "<br>");
        var testqVar = "全局變量q";
        /*如不屏蔽下句話,程序直接停在這了,因爲出錯了,不認識testGlobal,得把下一句和下下句換一下位置,就ok了 */
        //document.writeln("testGlobal is" + testGlobal);
        testGlobal = "全局變量global";
        document.writeln("value of 'abc' is " + abc + "<br>");
        var abc;
        testGlobalInVar = "全局變量globalInVar";
        function testSco()
        {
            var lll = "qqq";
            var testVar = "局部變量";  //此testVar非外面的testVar
            testqVar = "全局變量qchange";  //此testqVar就是外面的testqVar
            testGlobal = "全局變量globalchange";
            var testGlobalInVar = "局部變量global";  //此testGlobalInVar非外面的testGlobalInVar
            /*local variable is stronger than global variable.so "testVar" in the following statement means local variable.*/
            document.writeln("value of 'testVar' is : " + testVar + "<br>");
            document.writeln("value of 'testqVar' is : " + testqVar + "<br>");
            document.writeln("value of 'testGlobalInVar' is : " + testGlobalInVar + "<br>");
        }

        testSco();
        document.writeln("value of second 'test' is : " + testVar + "<br>");
        document.writeln("value of second 'testqVar' is : " + testqVar + "<br>");
        document.writeln("value of 'testGlobal' is : " + testGlobal + "<br>");
        document.writeln("value of 'testGlobalInVar' is : " + testGlobalInVar + "<br>");
    </script>
    
    <body>
    </body>
</html>

輸出結果:

window.testVar is 全局變量 | 全局變量
value of 'abc' is undefined
value of 'testVar' is : 局部變量
value of 'testqVar' is : 全局變量qchange
value of 'testGlobalInVar' is : 局部變量global
value of second 'test' is : 全局變量
value of second 'testqVar' is : 全局變量qchange
value of 'testGlobal' is : 全局變量globalchange
value of 'testGlobalInVar' is : 全局變量globalInVar 

例 3.2.2

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
    <script>

        var abc = "全局變量";
        function testscope()
        {
            /*
            refer to 上例 first. 馬克-to-win: because already defined local variable, but does not assign value, 
            so it is undefined. If we totally remove var abc = "局部變量"; alert(abc);
            will  print out 全局變量, but local "scope" will override the global "scope", it is undefined.
            so we can learn a lesson, if we use a local variable, we must first assign value, then we can use it.
            */
            document.writeln("函數內部賦值abc之前 : " + abc + "<br>");
            var abc = "局部變量";
            document.writeln("函數內部賦值abc之後 : " + abc + "<br>");
        }
        testscope();
        document.writeln("函數外部賦值abc之後 : " + abc + "<br>");
    </script>
    
    <body>
    </body>
</html>

輸出結果:

函數內部賦值abc之前 : undefined
函數內部賦值abc之後 : 局部變量
函數外部賦值abc之後 : 全局變量

例 3.2.2_1:

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
    <script>

        var abc = "全局變量";
        function testscope()
        {
            document.writeln("函數內輸出 : " + abc + "<br>");
        }
        testscope();
        document.writeln("函數外輸出 : " + abc + "<br>");
    </script>
    <body>
    </body>
</html>

輸出結果:

函數內輸出 : 全局變量
函數外輸出 : 全局變量

例 3.2.3(noblockScope)

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
    <script>
        function test()
        {
            /* 馬克-to-win: there are only global variable (outside of any function) and function variable, no block variable at all.*/
           /*note that in javascript, there is no block variable, only function variable, so m and z are function variable.*/
            for (var z = 0; z < 2; z++)
            {
                var m = 1;
                //m的作用範圍是整個函數內,而不是循環體內
                document.writeln("z is : " + z + "<br>");
            }
            //即使出了循環體,m和z的值依然存在
            document.writeln("z is : " +z + ", m is : " + m + "<br>");
        }
        /*document is a property of global object---window,so can directly use.*/
        test();
        document.writeln("馬克-to-win" + "<br>");
        /*the following statement is wrong because no global m is defined first, so nothing can be printed out*/
        document.writeln("m is : " + m + "<br>");
        document.writeln("馬克-to-win" + "<br>");
    </script>
    <body>
    </body>
</html>

輸出結果:

z is : 0
z is : 1
z is : 2, m is : 1
馬克-to-win

例 3.2.4(局部變量, 全局變量)

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>

    <script>
        function M1(arg1, arg2)
        {
        /*馬克-to-win:note that here if var m1=new M1(8,9); then this.qqq means m1's property, while
        if you directly call M1(2,3); then this.qqq means window's property. */
            this.qqq = arg1;
            /*note that here "bbb" means the windows's property*/
            bbb = arg2;
            /*the following "q" is a local variable, so inside another function, it can not be called. */
            var q = 3;
        }
        function M2()
        {
            document.writeln("value of 'bbb' is : " + bbb + "<br>");
            document.writeln("value of 'window.bbb' is : " + window.bbb + "<br>");
            document.writeln("value of 'this.bbb' is : " + this.bbb + "<br>");
            document.writeln("value of 'this.qqq' is : " + this.qqq + "<br>");
        //alert("q is"+ q);
        }

        var m1 = new M1(8, 9);
        m1.info = function()
        {
            document.writeln("value of 'this.qqq' inside of m1.info is : " + this.qqq + "<br>");
        };
        m1.info();
        /*note that the following mk.info(); must be commented out, otherwise, it report error, because mk does not have
        info() function, because the fucntion of info only belong to m1. this is also the difference between prototype
        and m1.info();  */
        //    var mk=new M1(8,9);
        //  mk.info();
        M2();
        document.writeln("<br>");
        document.writeln("attribute 'qqq' of 'this' outside of function is : " + this.qqq + "<br>");
        document.writeln("attribute 'bbb' of 'this' outside of function is : " + this.bbb + "<br>");
        document.writeln("attribute 'qqq' of 'm1' outside of function is : " + m1.qqq + "<br><br>");

        document.writeln("the second step ..." + "<br><br>");
        M1(2, 3);
        M2();
        document.writeln("<br>");
        document.writeln("attribute 'qqq' of 'this' outside of function is : " + this.qqq + "<br>");
        document.writeln("attribute 'bbb' of 'this' outside of function is : " + this.bbb + "<br>");
    </script>
    
    <body>
    </body>
</html>

輸出結果:

value of 'this.qqq' inside of m1.info is : 8
value of 'bbb' is : 9
value of 'window.bbb' is : 9
value of 'this.bbb' is : 9
value of 'this.qqq' is : undefined

attribute 'qqq' of 'this' outside of function is : undefined
attribute 'bbb' of 'this' outside of function is : 9
attribute 'qqq' of 'm1' outside of function is : 8

the second step ...

value of 'bbb' is : 3
value of 'window.bbb' is : 3
value of 'this.bbb' is : 3
value of 'this.qqq' is : 2

attribute 'qqq' of 'this' outside of function is : 2
attribute 'bbb' of 'this' outside of function is : 3

3)嵌套函數

例 3.3.1

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>

    <script>
        function outerFun(){
            var i = 0;
            function innerFun(){
                document.write("value of 'i' is : " + i + "<br>");
            }
            innerFun();
        }
        outerFun();
        /*note : here you can not call innerFun(), because it is inside another function outerFun, 
        so it will cause error.*/
        innerFun();
        document.write("馬克-to-win");
    </script>
    
    <body>
    </body>
</html>

輸出結果:

value of 'i' is : 0

4)Function用法

例 3.4.1

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>

    <script>
        /*馬克-to-win:When the Global object is created, it always has at least the following properties:
           Object object
           Function object
           Array object
           String object
           Boolean object
           Number object
           Date object
           Math object
           Value properties
       */

        /*Function的好處是, 函數體可以是運行時的一個傳入的動態字符串,
        for the Function class, the last parameter is
        function body, while the parameters before the last one are input arguments., 
        'x' can be changed to "x" */
        var a='return x + y;';
        var f = new Function('x', 'y',a ); // 等價於var f = function(x, y){return x + y;}
        document.write("value of f(1, 1) is : " + f(1, 1));
    </script>
    
    <body>
    </body>
</html>

輸出結果:

value of f(1, 1) is : 2 

5)構造函數的用法:

例 3.5.1

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>

    <script>
        function Student(name, age)
        {
            /* Note :later on we can use it in
            var doc = new ActiveXObject( "Microsoft.XMLDOM" );
                        doc.async="false";
                        doc.load(str);
            when a property has a this, means that this property is a member property.
            */
            this.name = name;
            this.age = age;
            this.parti = function()
            {
                document.writeln("名字是 : " + this.name + "<br>");
                document.writeln("年紀是 : " + this.age + "<br>");
            };
        }
        var p = new Student('jeri', 3);
        document.writeln("typeof p is : " + typeof(p) + "<br>");
        //typeof(p) is object
        p.parti();
        p.age = 4;
        p.parti();
        /*the following two methods can also access some properties.*/
        document.writeln('value of p["age"] is : ' + p["age"] + "<br>");
        document.writeln('value of p["a" + "ge"] is : ' + p["a" + "ge"] + "<br>");


        if (p instanceof Student) document.writeln("p是Student的實例<br>");
        /* javascript 中的對象全部是Object 的子類
        Because this object is the topmost parent object in the prototype inheritance hierarchy, all other object classes inherit its methods and properties. It's a close enough call that JavaScript 2.0 may well move it into the class-based object-oriented category at which time the prototype inheritance would be replaced with super-class/sub-class mechanisms and the arguments become null and void.  */
        /* When the Global object is created, it always has at least the following properties:
           Object object
           Function object
           Array object
           String object
           Boolean object
           Number object
           Date object
           Math object
           Value properties
       */
        if (p instanceof Object) document.writeln("p是Object的實例");
    </script>
    
    <body>
    </body>
</html>

輸出結果:

typeof p is : object
名字是 : jeri
年紀是 : 3
名字是 : jeri
年紀是 : 4
value of p["age"] is : 4
value of p["a" + "ge"] is : 4
p是Student的實例
p是Object的實例 

例 3.5.2

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>

    <script>
        function f2()
        {
            this.lll = "馬克-to-win";
            document.writeln("where is in f2 <br>");
            /*for new operator, the following statement got no use. */
            return 'Hello 馬克-to-win';
        }
        /*so f2 has dual role, one is ordinary function, another is that construactor, 
        see whether you use new operator or just simply call it.*/
        var f5 = f2();
        document.writeln("typeof f5 is : " + typeof f5 + "; typeof f2 is : " + typeof f2 + "; value of f5 is : " + f5 + "<br>");
        document.writeln("<br>");
        document.writeln("f5.lll is : " + f5.lll + "<br>'window.lll' is : " + window.lll + "<br>'lll' is : " + lll + "<br>");
        document.writeln("<br>");
        var f6 = new f2();
        document.writeln("typeof f6 : " + typeof f6 + " ; typeof f2 is : " + typeof f2 + "; value of f6 is :  " + f6 + "<br>");
        document.writeln("<br>");
        document.writeln("f6.lll is : " + f6.lll + "<br>'window.lll' is : " + window.lll + "<br>'lll' is : " + lll + "<br>");
        
        var zhanwei = "zhanwei";
    </script>
    
    <body>
    </body>
</html>

輸出結果:

where is in f2
typeof f5 is : string; typeof f2 is : function; value of f5 is : Hello 馬克-to-win

f5.lll is : undefined
'window.lll' is : 馬克-to-win
'lll' is : 馬克-to-win

where is in f2
typeof f6 : object ; typeof f2 is : function; value of f6 is : [object Object]

f6.lll is : 馬克-to-win
'window.lll' is : 馬克-to-win
'lll' is : 馬克-to-win

6)靜態方法和prototype(難)

例 3.6.1

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<script>
    /*note that 馬克-to-win: static variable's value has nothing to do with instance's variable's value.instance 名稱 can not 直接access static member like in java.
This is different from Java,比如下面例子中,Student.number=2,但是d1.number就爲undefined.This is different from Java,但在實例方法中(比如d1.info)可以訪問Student.number。這是和java中一樣的。或者說function外或任何地方都可以訪問Student.number。反過來,d1.age也可以在靜態方法中訪問,就像在function外一樣,任何地方都能訪問d1.age。String.prototype.abcd,這是給所有的實例加屬性而不是靜態屬性。*/
    function Student(number, agev)
    {
        this.age = agev;
        /*static variable's value can not be accessed by instance */
        Student.number = number;
        /*lb is local variable, but not a member variable because it is not modified by this. from outside it can not be accessed. refer to noblockScope.html */
        var lb = 0;
    }
    var d1 = new Student(1, 3);
    document.writeln("this的age屬性爲means window.age" + this.age + "<br>");
    document.writeln("d1的age屬性爲" + d1.age + "<br>");
    document.writeln("d1的number屬性爲" + d1.number + "<br>");
    document.writeln("通過Student訪問靜態number屬性爲" + Student.number + "<br>");
    document.writeln("d1的lb屬性爲" + d1.lb + "<br><hr>");
    d1.qixy = "abc";/*以隨意爲實例加屬性或方法*/
    document.writeln("可以隨意爲實例加屬性或方法see following,d1的qixy屬性爲" + d1.qixy + "<br><hr>");
    document.writeln("是否有靜態變量qixy" + Student.qixy + "<br><hr>");
    d1.info = function()/*此方法僅爲d1對象所用*/
    {
        document.writeln("對象的qixy屬性:" + this.qixy);

        document.writeln("對象的age屬性:" + this.age);
        /*下列話是合法的, 因爲不是this.number, 而是Student.number*/
        document.writeln("static method is " + Student.number);
    };
    Student.prototype.infop = function()/*此方法可以爲所有Student對象所用*/
    {
        document.writeln("對象的qixy屬性p:" + this.qixy);
        document.writeln("對象的age屬性p:" + this.age);
        /*下列話是合法的, 因爲不是this.number, 而是Student.number*/
        document.writeln("static method is " + Student.number);
    };
    Student.staticMethod = function()
    {
        /*下列話是合法的, 因爲是d1.age,就像在function外一樣,任何地方都能訪問d1.age*/
        document.writeln("d1的age屬性爲" + d1.age + "<br>");
        document.writeln("static method is " + Student.number);
    };
    d1.info();
    Student.staticMethod();
    var d2 = new Student(2, 4);
    /*the following statement can not be added, otherwise, it report error. because info is d1's method.
this is the beneit of prototype.prototype 能給類添加instance方法*/
    //    d2.info();
    d2.infop();
    d1.infop();
    document.writeln("d1的age屬性爲" + d1.age + "<br>");
    document.writeln("d1的number屬性爲" + d1.number + "<br>");
    document.writeln("d2的age屬性爲" + d2.age + "<br>");
    document.writeln("d2的number屬性爲" + d2.number + "<br>");
    document.writeln("通過Student訪問靜態number屬性爲" + Student.number + "<br>");
    Student.number = 3;
    document.writeln("通過Student訪問靜態number屬性爲" + Student.number + "<br>");
    Student.number1 = 31;
    document.writeln("通過Student訪問靜態number1屬性爲" + Student.number1 + "<br>");
/*馬克-to-win: abc是靜態屬性。 只能通過String.abc這樣靜態的屬性來訪問。通過以下的as.abc這樣的
實例屬性是訪問不着的。用以下的String.prototype.abcd,這是給所有的實例加屬性而不是靜態屬性,用as.abcd這樣的實例屬性就能訪問着了*/
    /*When the Global object is created, it always has at least the following properties:
       Object object       Function object       Array object       String object
       Boolean object       Number object       Date object       Math object
       Value properties
   */
    String.abc = "qixy";
    document.writeln("通過String訪問靜態abc屬性爲" + String.abc + "<br>");
    var as="aString"
    document.writeln("as.abc is " +as.abc  + "<br>");
    String.prototype.abcd="qixyqixy";
    document.writeln("as.abcd is " +as.abcd  + "<br>");
    /*a property can be nonexist, it is still can be printed out.*/
    document.writeln("d1的noexist屬性爲" + d1.noexist + "<br><hr>");
    /* p3 does not exists, error is generated.so program will stop here. */
    document.writeln("p3的lb屬性爲" + p3.lb + "<br><hr>");
    document.writeln("d1的noexist屬性爲" + d1.noexist + "<br><hr>");
</script>
here is body which is  after the tag of script

輸出結果:

this的age屬性爲means window.ageundefined
d1的age屬性爲3
d1的number屬性爲undefined
通過Student訪問靜態number屬性爲1
d1的lb屬性爲undefined


可以隨意爲實例加屬性或方法see following,d1的qixy屬性爲abc


是否有靜態變量qixyundefined


對象的qixy屬性:abc 對象的age屬性:3 static method is 1 d1的age屬性爲3
static method is 1 對象的qixy屬性p:undefined 對象的age屬性p:4 static method is 2 對象的qixy屬性p:abc 對象的age屬性p:3 static method is 2 d1的age屬性爲3
d1的number屬性爲undefined
d2的age屬性爲4
d2的number屬性爲undefined
通過Student訪問靜態number屬性爲2
通過Student訪問靜態number屬性爲3
通過Student訪問靜態number1屬性爲31
通過String訪問靜態abc屬性爲qixy
as.abc is undefined
as.abcd is qixyqixy
d1的noexist屬性爲undefined


here is body which is after the tag of script

 

prototype

注:prototype作用就是給某個類增加一個實例方法。

例 3.6.2

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<script>
  /*When the Global object is created, it always has at least the following properties:
       Object object       Function object       Array object       String object
       Boolean object       Number object       Date object       Math object
       Value properties
   */
    Array.prototype.mymethod = function(number)
    {
        var result = -1;
/*注意mymethod功能是找出某數在數組中出現的位置。作爲Array的一個function,可以訪問Array的屬性this.length, 參見上一個prototype的例子,  
    Student.prototype.infop = function()/*此方法可以爲所有Student對象所用*/
    {
        document.writeln("對象的qixy屬性p:" + this.qixy);
        document.writeln("對象的age屬性p:" + this.age);
        /*下列話是合法的, 因爲不是this.number, 而是Student.number*/
        document.writeln("static method is " + Student.number);
    };
*/
        for (var i = 0; i < this.length; i ++)
        {
            if (this[i] == number)
            {
                result = i;
                break;
            }
        }
        return result;
    }
    var a = [3,5,23,4,67];
    document.writeln(a.mymethod(4));
    var zhanwei = "zhanwei";
</script>

輸出結果:

3

7)onload

注:onload就是等頁面加載完後才執行。

例 3.7.1

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <SCRIPT LANGUAGE="JavaScript">
        <!--
        function a(b)
        {
document.write("part 1");
        }

        //-->
    </SCRIPT>
</head>
<body onload='a("a","b","c")'>
part2,onload 會在part1和part2打印之後再執行。
</body>

輸出結果:

part 1

例 3.7.2

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <script LANGUAGE="JavaScript">
        <!--
        function a(b)
        {
document.write("part 11");
        }
document.write("part 5");
        //-->
    </script>
</head>
<body onload='a("a","b","c")'>
part2,onload 會在part 11和part2打印之後再執行。
</body>

輸出結果:

part 11

例 3.7.3

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <script language="JavaScript">
        <!--
        function a(b)
        {
document.write(document.body.innerHTML + "part 11");
        }
document.write("part 5");
        //-->
    </script>
</head>
<body onload='a("a","b","c")'>
part2,onload 會在part 11和part2打印之後再執行。
</body>

輸出結果:

8)arguments

例 3.8.1

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<script>
    /*  馬克-to-win:when there are n functions with the same function name, only the last one is used.  */
    function test()
    {
        document.writeln("no argument constructor.");
    }
    function test(person)
    {
        document.writeln("馬克-to-win2");
        /*Function.arguments[] (Collection) The values passed to the function when it is called.
        馬克-to-win: inside function,we can directly use arguments.
        */
        var n = arguments.length;
        document.writeln("n is " + n);
        for (var i = 0; i < n; i++)
        {
            document.writeln("馬克-to-win3");
            document.writeln(arguments[i])
        }
        document.writeln(person);
        document.writeln(typeof(person) + "is typeof");
    }
    /*when no param, undefined is passed in. no overloaded function concept.*/
    test();
    /*when there is no this function, program stops here.*/
    change();
    document.writeln("finally");
</script>

輸出結果:

馬克-to-win2 n is 0 undefined undefinedis typeof 

例 3.8.2

<head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <script language="javascript">
        <!--
        function a(b)
        {
            document.write(document.body.innerhtml + "b is " + b);
            /*function.arguments[] (collection)
the values passed to the function when it is called.with firebug, we can directly see arguments*/
            var n = arguments.length;
            document.write(n);
            for (var i = 0; i < n; i++)
            {
                document.write(arguments[i]);
                document.write("ok");
            }
        }
        document.write("part 1");
        //-->
    </script>
</head>
<body onload='a("a","b","c")'>
part2,onload 會在part1和part2打印之後再執行。
</body>

輸出結果:

part 1 part2,onload 會在part1和part2打印之後再執行。 b is a3aokbokcok

9)Object

例 3.9.1

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<script>
        /*馬克-to-win:When the Global object is created, it always has at least the following properties:
       Object object       Function object       Array object       String object
       Boolean object       Number object       Date object       Math object
       Value properties
   */
    var oi = new Object();
    oi.name = 'mark';
    oi.height = 4;
    function xxx()
    {
        document.writeln("對象的name屬性:" + this.name);
        document.writeln("<br>");
        document.writeln("對象的height屬性:" + this.height);
    }
    oi.list = xxx;
    oi.list();
    document.writeln(oi["name"] + oi["height"]);
</script>

輸出結果:

對象的name屬性:mark
對象的height屬性:4 mark4 

10)json

例 3.10.1

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<script>
    var student =
    {    name : 'mark',
        age : 3 ,
        classes : ['小' , '中' , "大"],
        /* 馬克-to-win:class is an array of string, also parents is also an array of json object. */
        parents :[
            {
                name : 'father',
                age : 42,
                salary : 'low'
            }
            ,
            {
                name : 'mother',
                age : 37,
                salary : 'high'
            }
        ]
    };
    document.writeln(student.name);
    document.writeln("<hr>");
    document.writeln(student.age);
    document.writeln("<hr>");
    document.writeln(student.classes[1]);
    document.writeln("<hr>");
    document.writeln(student.parents[1].name);
</script>

輸出結果:

mark


3



mother
 

11)for in Array

例 3.11.1

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <script type="text/javascript">
        var a=['hello','teacher','馬克-to-win'];
        for(var iii in a){
            this.document.write('inidex'+iii+'的值是'+a[iii]+"<br>");
        }
    </script>
</head>
<body>

</body>
</html>

輸出結果:

inidex0的值是hello
inidex1的值是teacher
inidex2的值是馬克-to-win

12)函數指針

例 3.12.1

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <script type="text/javascript">

        function sortnumber(a, b)
        {
            document.writeln(a + b);
        }
        function sortq(sortnumberqqq)
        {
            document.writeln("馬克-to-win");
            sortnumberqqq(1, 2);
            return 6;
        }
        /* note that it will report error if we write the following statement as document.write("test "+sortq(sortnumberqixy));
       note that here sortnumber is a function pointer.
        下面這句話是先執行sortq(sortnumber),等返回值以後,再執行document.write("test "*/
        document.write("test " + sortq(sortnumber));

    </script>
</head>

<body>

</body>
</html>

輸出結果:

馬克-to-win 3 test 6

13)call()和apply()

注:call是在特定的作用域中調用函數。

例 3.13.1
 

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>

    </title>
    <script type="text/javascript">
        function A(name) {
            this.name = name;
        }
         A.prototype.info = function()
         {
         /*如果下局解開屏蔽,最後結果則打印出就爲A,結論就是在call時,先在A裏找this.name,如果找不着,則用b環境裏找,現在A的構造函數從來沒有執行過,所以最後用的是B環境的name,見下一個例子*/
                //this.name="A";
                return "A的名字是 "+this.name;
         }


        function B(agev)  {
            this.age=agev;
            this.name="I am B"
        }
            var b = new B(2);
    var tmp =A.prototype.info;
    document.writeln(tmp.call(b));

    var zhanwei="zhanwei";

    </script>
</head>
<body>

輸出結果:

A的名字是 I am B 

 

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>

    </title>
    <script type="text/javascript">
        function A(name,col) {
 /*實參一個,但形參2個,所以最後一個參數color爲undefined,id和name都有,所以是把B給衝了的,但age是用了B的*/
            this.color=col;
            this.id="a";
            this.name = name;
            return "A(name) 名字是 "+this.id+this.name+this.age+this.color;
        }
         A.prototype.info = function()
         {
                return "名字是 "+this.name;
         }
        A.prototype.country = "China";

        function B(agev)  {
            this.id="b";
            this.age=agev;
            this.name="this is B"
        }
            var b = new B(2);

    document.writeln(A.call(b, "馬克-to-win"));
    var zhanwei="zhanwei";

    </script>
</head>
<body>

 輸出結果:

A(name) 名字是 a馬克-to-win2undefined 

例 3.13.2

<script>
/*
他們的用途相同,都是在特定的作用域中調用函數。screenX是window的一個field。
 3、接收參數方面不同,apply()接收兩個參數,一個是函數運行的作用域(this),另一個是參數數組。
 call()方法第一個參數與apply()方法相同,但傳遞給函數的參數必須列舉出來。 */
    function sum(num1, num2) {
        return screenX+num1 + num2;
    }
    document.writeln(screenX+" is screenX");
    document.writeln(sum.call(window, 10, 10)); //20+screenX
    document.writeln(sum.apply(window,[10,20])); //30+screenX

</script>

輸出結果:

-4 is screenX 16 26 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章