2012-02-21 18 views
45

這段代碼也提到了什麼? 用於標記匿名函數的Javascript「冒號」?

queryString: function() { 

//some code 

} 

我測試了它在Web控制檯(火狐),但它不會執行,所以我認爲它不等同於function queryString() {}

那究竟是什麼?

+0

應該是:queryString = – 2012-02-21 20:46:53

+4

它用於定義對象或類中的函數,所以我認爲你已經把它從對象的範圍中取出。 – Dampsquid 2012-02-21 20:48:14

回答

57

你缺少了一些代碼,但我認爲一個對象聲明其本身而言是這樣的:

var obj = { 
    queryString: function() { 
    //some code 
    } 
}; 
obj.queryString(); 

它指定一個函數作爲對象文本的屬性。這將是相同的:

var obj = {}; 
obj.queryString = function() { ... }; 
obj.queryString(); 

一般來說,對象文本語法如下:

{ key: value, otherKey: otherValue }; 

所以這並沒有在控制檯工作的原因是,它沒有被封閉在{}字符,表示對象字面量。而且這個語法只在對象文本中有效。

4

定義對象及其屬性時使用:

var obj = { 
    queryString: function() { 
     //some code 
    } 
} 

Now obj.queryString是你的功能。

9

這可能是一個地圖/對象的聲明中,像這樣:

var obj = { 
    queryString: function() { 
     alert('here'); 
    }, 
    eggs: function() { 
     alert('another function'); 
    } 
}; 

obj.queryString(); 
+0

所以它就像那個物體的屬性:)謝謝! – knownasilya 2012-02-23 03:28:13

1

什麼

queryString: function() { 

//some code 

} 

意思是你可以使用的queryString()調用,它指的是功能。如果你想在你的javascript中定義一個類(或者一個僞類; P),通常會使用這種引用。事情是這樣的,

var application= { namespace: {} }; 

application.namespace.class_name = function(){ 

    function constructor(){ 
    return { 
    exposed_property1 : property1, 
    exposed_property2 : property2, 
    ... 
    ... 
    } 
    } 
    //Write property/functions that you want to expose. 
    // Write rest of the function that you want private as function private(){} 
}; 

所以,現在你可以創建CLASS_NAME對象,並使用它來訪問property1,property2等代碼的任何其它部分,

3

這是一個標籤https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

var i, j; 

loop1: 
for (i = 0; i < 3; i++) {  //The first for statement is labeled "loop1" 
    loop2: 
    for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" 
     if (i == 1 && j == 1) { 
     continue loop1; 
     } 
     console.log("i = " + i + ", j = " + j); 
    } 
} 

// Output is: 
// "i = 0, j = 0" 
// "i = 0, j = 1" 
// "i = 0, j = 2" 
// "i = 1, j = 0" 
// "i = 2, j = 0" 
// "i = 2, j = 1" 
// "i = 2, j = 2" 
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"