2014-08-28 124 views
2
var app = new Vue({ 
el: '#main', 
template: $("#products-template").text(), 
data: { 
loading: true, 
products: [] 
}, 
ready: function() { 
var self = this; 
$.getJSON(url, function(fbresults){ 
self.products = fbresults.data; 
self.loading = false; 
}); 
} 
}); 

有什麼區別使用=和:在javascript

var app = new Vue({ 
el= '#main', 
template= $("#products-template").text(), 
data= { 
loading= true, 
products= [] 
}, 
ready= function() { 
var self = this; 
$.getJSON(url, function(fbresults){ 
self.products = fbresults.data; 
self.loading = false; 
}); 
} 
}); 

在上面的代碼片段「=」以及「:」被使用,所以我們什麼時候需要用=當使用:,目的是什麼:主要是

回答

1

聲明對象文字的屬性時這裏使用的冒號:

{ 
    key: value, 
    key2: value2 
} 

等於運算符的值分配給變量或表達式:

foo = 5; 
obj.key = value; 

在你的例子中,冒號定義了傳入的對象的屬性。它更明顯,如果你使用正確的縮進:

var app = new Vue({ 
    el: '#main', 
    template: $("#products-template").text(), 
    data: { 
     loading: true, 
     products: [] 
    }, 
    ready: function() { 
     var self = this; 
     $.getJSON(url, function(fbresults){ 
      self.products = fbresults.data; 
      self.loading = false; 
     }); 
    } 
}); 
1

:指定object literal,=內的值賦給對象字面值以外的值。

例如:

// at this point we're outside of an object, so we use = 
var hello = "world"; 

var someObject = { 
    // now we're inside an object literal definition, so we use : 
    hello: "world" 
}; 
1

你可以用一個簡單的例子明白這一點:

var x = { 
    obj1: 'text1', //declaring properties of an object literal 
    obj2: 'text2' 
}; 

在功能上等同於

var y = new Object(); 
obj1.a = 'text1'; //assigning a value to the expression 
obj2.b = 'text2'; 
相關問題