[英]Javascript function, extend an object with an extension
This piece of code is from Addy Osmani's online book, " Learning JavaScript Design Patterns ". 这段代码来自Addy Osmani的在线书籍“ 学习JavaScript设计模式 ”。
// Extend an object with an extension
function extend( extension, obj ){
for ( var key in extension ){
obj[key] = extension[key];
}
}
It claims it can extend an object with an extension. 它声称它可以扩展具有扩展名的对象。 It work well in the sample on the book.
它在本书的样本中运作良好。 The
controlCheckbox
can function well for both definitions, Subject
and DOM checkbox
. controlCheckbox
可以很好地用于定义, Subject
和DOM checkbox
。
<input id="mainCheckbox" type="checkbox"/>
...
var controlCheckbox = document.getElementById( "mainCheckbox" ),
...
extend( new Subject(), controlCheckbox );
...
controlCheckbox["onclick"] = new Function( "controlCheckbox.Notify(controlCheckbox.checked)" );
But I just can't get the point why it is extended ? 但我只是不明白它为何延长 ? The function definition of
extend
looks like overrding , instead of extending , controlCheckbox
from an DOM checkbox
to Subject
, in my poor eyes. 在我的可怜的眼中,
extend
的函数定义看起来像是覆盖而不是将 controlCheckbox
从DOM checkbox
扩展到Subject
。 Can someone help me understand? 有人可以帮我理解吗?
What extend
does is add all attributes from extension
to obj
and overwrite the ones already existing. 什么
extend
确实是增加所有属性extension
到obj
和覆盖那些已经存在。
When you say obj['attr'] = 'foo'
in javascript, you create the attribute attr
in the object obj
and assign foo
to it. 当你在javascript中说
obj['attr'] = 'foo'
时,你在对象obj
创建属性attr
并为它指定foo
。 If attr
already exists in obj
, you will overwrite it with foo
. 如果
attr
在已经存在obj
,你会覆盖它foo
。
An alternative syntax would be obj.attr='foo'
, but this way, you can't use dynamic attribute names (variables, like in your example key
is) 另一种语法是
obj.attr='foo'
,但是这样,你就不能使用动态属性名称(变量,就像在你的示例key
中一样)
Some useful links: 一些有用的链接:
Here is an example: 这是一个例子:
function extend( extension, obj ){
for ( var key in extension ){
obj[key] = extension[key];
}
}
var obj = { a: 1, b: 2 },
extension = { b: 20, c: 30 };
console.log("Before: ", obj);
extend(extension, obj);
console.log("After: ", obj);
Output: 输出:
Before: Object {a: 1, b: 2}
After: Object {a: 1, b: 20, c: 30}
It's easy to see what's happened: 很容易看出发生了什么:
a
didn't exist in extension
, so it remained unchanged . a
在extension
不存在,因此它保持不变 。 b
existed in both objects, so it was overwritten by extension
's field b
. b
存在于两个对象中,因此它被extension
字段b
覆盖 。 c
existed only in extension
, so it was added to obj
. c
仅存在于extension
,因此它被添加到obj
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.