javascript 中function(){},new function(),new Function(),Function 簡單介紹

來源:互聯網
上載者:User

標籤:方法   理解   關係   對象   寫法   new   介紹   最大   tor   

函數是JavaScript中很重要的一個語言元素,並且提供了一個function關鍵字和內建對象Function,下面是其可能的用法和它們之間的關係。

function使用方式
 var foo01 = function() //或 function foo01() {       var temp = 100;       this.temp = 200;       return temp + this.temp;   }   alert(typeof(foo01));  // function  alert(foo01());          // 300 

最普通的function使用方式,定一個JavaScript函數。兩種寫法表現出來的運行效果完全相同,唯一的卻別是後一種寫法有較高的初始化優先順序。在大擴號內的變數範圍中,this指代foo01的所有者,即window對象。

new function()使用方式
var foo02 = new function()   {       var temp = 100;       this.temp = 200;       return temp + this.temp;   }   alert(typeof(foo02));    //object  alert(foo02.constructor());   //300   

這是一個比較puzzle的function的使用方式,好像是定一個函數。但是實際上這是定一個JavaScript中的使用者自訂對象,不過這裡是個匿名類。這個用法和函數本身的使用基本沒有任何關係,在大擴號中會構建一個變數範圍,this指代這個範圍本身。(理解為執行個體化匿名類)

new Function()使用方式
var foo3 = new Function(‘var temp = 100; this.temp = 200; return temp + this.temp;‘);   alert(typeof(foo3));  //object alert(foo3());           //300

使用系統內建函數對象來構建一個函數,這和方法一中的第一種方式在效果和初始化優先順序上都完全相同,就是函數體以字串形式給出。

Function()使用方式
var foo4 = Function(‘var temp = 100; this.temp = 200; return temp + this.temp;‘);   alert(typeof(foo4));     //function alert(foo4());              //300

這個方式是不常使用的,效果和方法三一樣,不過不清楚不用new來產生有沒有什麼副作用,這也體現了JavaScript一個最大的特性:靈活!能省就省。(不推薦使用)

javascript 中function(){},new function(),new Function(),Function 簡單介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.