【Javascript】—— 1 方法function的高級特性

  本篇僅僅對於function做簡單的講解,在javascript中function不單單是方法,它實際上是一個變量,所以擁有本身的屬性,而且能夠當作參數傳遞給其餘的方法。javascript

  那麼傳統的方法,按照java的寫法應該以下的建立:html

<!-- 普通的function -->
            function testFunc1(name,age){ console.log("name"+name+" age"+age); } testFunc1("xingoo",26);

  可是咱們在javascript中也能夠經過var聲明變量的方式來建立,可是須要使用Function方法。java

  Function方法,前幾個參數是咱們建立的方法的參數,最後一個是它的方法體。spa

<!-- 經過建立變量方式,建立的function -->
            var testFunc2 = new Function("name","age","console.log('name'+name+' age'+age)"); testFunc2("halo",25);

  方法還有幾個比較經常使用的屬性:code

  length 參數的個數htm

  toString() 能夠獲取方法的源碼,若是採用第二種方法建立的方法則方法名會以anonymous來代替。blog

  valueOf() 做用相似toString()ip

  下面看一下能夠運行的代碼:源碼

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            <!-- 普通的function -->
            function testFunc1(name,age){ console.log("name"+name+" age"+age); } testFunc1("xingoo",26); <!-- 經過建立變量方式,建立的function -->
            var testFunc2 = new Function("name","age","console.log('name'+name+' age'+age)"); testFunc2("halo",25); console.log(testFunc1.length); console.log(testFunc1.toString()); console.log(testFunc2.toString()); console.log(testFunc2.valueOf()); </script>
    </body>
</html>

  運行結果爲io

相關文章
相關標籤/搜索