这些物体相等吗?
var Widget = new Class({
Implements: Options,
options: {
color: '#fff',
size: {
width: 100,
height: 100
}
},
initialize: function(options){
this.setOptions(options);
}
});
var myWidget = new Widget({
color: '#f00',
size: {
width: 200
}
});
//myWidget.options is now: {color: #f00, size: {width: 200, height: 100}}
// Deep copy example
var mySize = {
width: 50,
height: 50
};
var myWidget = new Widget({
size: mySize
});
(mySize == myWidget.options.size) // false! mySize was copied in the setOptions call.
来自此处
myWidget.options.size 也应该是
{
width: 50,
height: 50
};
为什么 (mySize == myWidget .options.size) // 错误! ?
var Widget = new Class({
Implements: Options,
options: {
color: '#fff',
size: {
width: 100,
height: 100
}
},
initialize: function(options){
this.setOptions(options);
}
});
var myWidget = new Widget({
color: '#f00',
size: {
width: 200
}
});
//myWidget.options is now: {color: #f00, size: {width: 200, height: 100}}
// Deep copy example
var mySize = {
width: 50,
height: 50
};
var myWidget = new Widget({
size: mySize
});
(mySize == myWidget.options.size) // false! mySize was copied in the setOptions call.
from here
myWidget.options.size should be also
{
width: 50,
height: 50
};
Why is (mySize == myWidget.options.size) // false! ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不是很明显,但您从示例中复制的注释告诉您原因。
对象上的等于是实例上的。 setOptions 复制 mySize。它在初始化时运行。
除非你问的是我错过的更复杂的问题。
Not to be obvious, but the comment that you copied from the example tells you why.
Equals on an object is to the instance. setOptions copies the mySize. It runs when it is initialized.
Unless you are asking a more complex question that I missed.
类似的东西是行不通的,因为它不检查对象的值,而是检查对象的身份:
所以如果你想比较两个对象,你必须编写类似的东西
Something like that won't work because it doesn't checks the values of the objects, but the identity of the objects:
So if you want to compare two object you have to write something like that
正如 @styrr 所说,比较 2 个对象是没有意义的,但您可以比较对象的序列化表示:
虽然您最好比较单个值,但它更便宜。
另外,请查看
Object.clone()
以取消引用。默认情况下,对象通过引用传递,但在选项的情况下,它们被取消引用。 IE 如果您更改mySize.width
,它不会更改您通常会得到的instance.options.size.width
。comparing 2 objects is meaningless as stated by @styrr but you can compare the serialised representation of the objects instead:
though you are better off comparing individual values, it's cheaper.
Also, look into
Object.clone()
to dereference. By default, objects are passed by reference but in the case of options, they are dereferenced. I.E. if you changemySize.width
, it won't changeinstance.options.size.width
, which you would get normally.使用 underscorejs.js isEqual 比较 JSON 对象 http://underscorejs.org/#isEqual
Use underscorejs.js isEqual to compare JSON objects http://underscorejs.org/#isEqual