2015-11-10 29 views
1

這裏是一個僞類的例子在IIFE在JavaScript中,在IIFE中包裝僞類有什麼好處?

// cow.js 
(function(exports) { 
    "use strict"; 

    function Cow(name) { 
    this.name = name || "Anon cow"; 
    } 
    exports.Cow = Cow; 

    Cow.prototype = { 
    greets: function(target) { 
     if (!target) 
     throw new Error("missing target"); 
     return this.name + " greets " + target; 
    } 
    }; 
})(this); 

什麼是是,在隨後的好處:

"use strict"; 

    function Cow(name) { 
    this.name = name || "Anon cow"; 
    } 
    exports.Cow = Cow; 

    Cow.prototype = { 
    greets: function(target) { 
     if (!target) 
     throw new Error("missing target"); 
     return this.name + " greets " + target; 
    } 
    }; 

不要這兩個最終增加奶牛的構造函數'功能到全球範圍?

cow.js文件正在通過HTML文檔包含在腳本標記中。這意味着this的值是窗口。這兩個示例將用於添加函數的全局範圍不是那麼相同嗎?

有人可以提供一個在模塊或不同範圍內使用它的例子嗎?

這不是重複的,如下面的相關問題IFFE並不需要一個參數 - What is the purpose of wrapping whole Javascript files in anonymous functions like 「(function(){ … })()」?

的代碼是從這裏複製:https://nicolas.perriault.net/code/2013/testing-frontend-javascript-code-using-mocha-chai-and-sinon/

+1

.P.r.i.v.a.c.y。 – Tushar

+1

@Tushar你能否詳細解釋一下? – Daryn

+0

在第二個例子中,Cow成爲一個全局方法(假設它是在窗口範圍內定義的,所以它變成了window.Cow),而它不在第一個例子中。 –

回答

0

不同的是範圍 - 在第一在一個匿名函數範圍內定義所有內容,第二種情況在全局範圍內定義。 IIFE的好處是模塊封裝,您可以在每個模塊中定義一個具有相同名稱的函數/類而不會影響另一個模塊。

+0

我已經添加了更多的細節問題,關於這個腳本是通過HTML頁面被包含的事實。這是不是意味着兩個版本都添加了Cow-窗口範圍? – Daryn

相關問題