簡體   English   中英

單獨聲明 function 或將其附加到 window 有什么區別?

[英]What's the difference between declaring a function by itself or attaching it to window?

抱歉,這個標題可能沒有多大意義,但我想知道的是:

window.myfunc = function(){}

function myfunc(){}

使用 jsfiddle,這些功能似乎僅在附加到 window 時才起作用。 我假設這與它如何設置以分別讀取 javascript 和 html 有關,但除此之外沒有區別嗎?

第一個保證 function 是全球性的,將在任何地方提供。

第二個做同樣的事情。 但第二個將采用嵌入它的第一個 function 的 scope。

第一種情況:

function foo()  {
   window.bar = function (){}
}
foo();
bar(); // is valid;

第二種情況

function foo()  {
    function bar(){}
}
foo();
bar(); // will fail

我希望這對你現在有意義

在全局 scope 中,有一些細微的差別:

Function 聲明被“提升”到其封閉 scope 的“頂部”,它們在代碼的實際執行開始之前被評估和初始化,這意味着如果你願意,你甚至可以在 ZC1C42145268E618394D 定義之前的某個點使用它們例子:

console.log(typeof foo); // "function"
console.log(foo());      // "bar"

function foo () {
  return "bar";
}

注意:如果您在 Firebug 中嘗試上述代碼段,它將顯示不同的行為,這是因為 Mozilla 實現支持函數作為語句,並且 Firebug 評估是在內部完成的,在try-catch塊內,將上述代碼包含在 function 中將顯示所描述的行為。

分配發生在運行時,因此foo的值只有在這發生之后才可用。

Function declarations also are bound as non-deletable properties of the lexical enviroment where they are bound, in the global scope, declarations are bound as properties of the global object, which is the top-most object at the scope chain, for example:

function foo() {
  //..
}

console.log(delete window.foo); // false
console.log(typeof foo);        // "function"

window.bar = function() {
  //..
}

console.log(delete window.bar); // true
console.log(typeof bar);        // "undefined"

沒有區別。 除了不同的聲明類型有: var functionName = function() {} vs function functionName() {}

所有全局變量實際上都是 window object 的屬性。

IE

g = 1;
alert(window.g);

警報 1

區別(除了 Ibu 的回答中提到的 scope 之外)是功能何時可用。

在執行任何代碼之前創建聲明的函數:

foo();  // no error

function foo(){}

而那些由表達式創建的只有在執行分配它們的代碼后才可用:

foo();  // error, foo is created by declaration with 'var'
        // but function hasn't been assigned yet
        // so can't call it

var foo = function (){}

 // call foo() here

Creating functions using assignment to window.funcName in the global scope is pointless and potentially harmful (the user agent may not be a browser and may not have a window object), just use a function declaration.

在另一個 function 中,應將此類函數創建為全局 object 的屬性,例如

(function(global) {
  global.foo = function(){}
)(this));

在瀏覽器中, global === window (有一些例外,沒有規范說必須如此,但通常是這樣)但在其他環境中,不需要window ZA8CFDE6331BD59EB2AC96F8911C4B66.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM