[英]The Definitive Guide (6ed) error?
/*
* Copy the enumerable properties of p to o, and return o.
* If o and p have a property by the same name, o's property is overwritten.
* This function does not handle getters and setters or copy attributes.
*/
function extend(o, p) {
for(prop in p) { // For all props in p.
o[prop] = p[prop]; // Add the property to o.
}
return o;
}
/*
* Return a new object that holds the properties of both o and p.
* If o and p have properties by the same name, the values from o are used.
*/
function union(o,p) { return extend(extend({},o), p); }
I think for union , he meant "values from p are used".我认为对于union ,他的意思是“使用来自 p 的值”。
I did the test on Chrome.我在 Chrome 上做了测试。 Am I wrong?
我错了吗? Sorry.
对不起。 I tend to be very caution when I am learning, especially this is the #1 book for Javascript, and 6ed is recent.
我在学习时往往非常谨慎,尤其是这是 Javascript 的第一本书,而 6ed 是最近的。
var o = {x:1}
变量 o = {x:1}
var p = {x: 2}
变量 p = {x: 2}
function extend(o,p){
function 扩展(o,p){
for(prop in p) o[prop] = p[prop]; return o;
}
}
function union(o,p){
function union(o,p){
return extend(extend({},o),p);
var g = union(o,p)
var g = union(o,p)
gx
gx
2
2
Thank you.谢谢你。
yeah it should read the properties from p
are kept and o
are overwritten.是的,它应该从
p
中读取的属性被保留并且o
被覆盖。
Though when writing this code it is a little safer to do this:尽管在编写此代码时这样做会更安全一些:
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
// now you know it is actually a property on obj and not inherited from elsewhere
}
}
Flannigan's book is considered the " least bad " book on javascript, so use with caution. Flannigan 的书被认为是 javascript 上“最不坏”的书,因此请谨慎使用。 For example, in the extend function the variable prop is not declared and the following:
例如,在扩展function 中,变量prop未声明,如下所示:
for(prop in p) { // For all props in p.
o[prop] = p[prop];
}
should really include a hasOwnProperty test, otherwise it will copy inherited enumerable properties also:应该真正包含一个hasOwnProperty测试,否则它也会复制继承的可枚举属性:
for (var prop in p) {
if (p.hasOwnProperty(prop)) {
o[prop] = p[prop];
}
}
And yes, the term "union" is probaby misleading to anyone who tries to apply set theory rigorously to objects.是的,“并集”这个词很可能会误导任何试图将集合论严格应用于对象的人。 If o already has a property with the same name as one on p , then it will be assigned the same value as the one on p (effectively overwriting the value of the one on o ).
如果o已经有一个与p上的 one 同名的属性,那么它将被分配与p上的相同的值(有效地覆盖o上的值)。
I think he is trying to show that existing properties of o that don't have equivalents on p are not changed or deleted.我认为他试图表明o在p上没有等价物的现有属性不会被更改或删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.