2014-08-28 138 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';