简体   繁体   English

Javascript函数,用扩展名扩展对象

[英]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确实是增加所有属性extensionobj和覆盖那些已经存在。

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: 很容易看出发生了什么:

  1. Field a didn't exist in extension , so it remained unchanged . 字段aextension不存在,因此它保持不变
  2. Field b existed in both objects, so it was overwritten by extension 's field b . 字段b存在于两个对象中,因此它被extension字段b 覆盖
  3. Field c existed only in extension , so it was added to obj . 字段c仅存在于extension ,因此它被添加obj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM