這裏是一個僞類的例子在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/
.P.r.i.v.a.c.y。 – Tushar
@Tushar你能否詳細解釋一下? – Daryn
在第二個例子中,Cow成爲一個全局方法(假設它是在窗口範圍內定義的,所以它變成了window.Cow),而它不在第一個例子中。 –