在什么情况下不默认需要一个功能? [英] In what cases does defaults need to be a function?
问题描述
我开始看 localtodos
应用程序,可以看到,这code使得它的功能。我不知道如何做出这样的选择。我的假设是,直到你调用不同的功能和对象的文字将立即PTED间$ P $函数中的code未运行。
I started by looking at the localtodos
app and can see that this code makes it a function. I don't know how to make this choice. My assumption is that the code in the function is not run untill you call the function unlike and object literal which will be interpreted immediately.
下面是用例:
var FavoritesRow = Backbone.Model.extend({
Name: 'FavoritesRow',
defaults: function () {
return {
url: "http://www.google.com",
title: "google",
favicon: "http://www.google.com/favicon.ico",
tag: "search"
};
}
});
我应该遵循
但什么规则/规则带来什么影响?
But what rule / rules should I follow in general?
推荐答案
请记住,在JavaScript中,对象是按引用传递的,所以如果
你有一个对象作为默认值,它会在所有共享
实例。取而代之的是,默认为函数。
Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Instead, define defaults as a function.
比较
var M = Backbone.Model.extend({
defaults: {
obj: {}
}
});
var m1 = new M();
var m2 = new M();
console.log(m1.get('obj') === m2.get('obj'));
// ==> outputs true
http://jsfiddle.net/nikoshr/6ctZ2/
和
var M = Backbone.Model.extend({
defaults: function() {
return {
obj: {}
};
}
});
var m1 = new M();
var m2 = new M();
console.log(m1.get('obj') === m2.get('obj'));
// ==> outputs false
http://jsfiddle.net/nikoshr/6ctZ2/1/
使用功能可以让你定义默认数组或对象不分享他们在类的所有实例。
Using a function will let you define default arrays or objects without sharing them on all instances of the class.
这篇关于在什么情况下不默认需要一个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!