我有一个简单的“扩展”方法,设置如下:
extend: function(source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
myThing[k] = source[k];
}
}
return myThing;
}
你喜欢用它
myThing.extend({
newObj: {
myFunc: function () { console.log('things'); }
}
});
效果很好。
但是,我很乐意添加让其他一些代码稍后调用它的功能:
myThing.extend({
newObj: {
mySecondFunc: function () { console.log('things'); }
}
});
而且我应该能够同时调用 myThing.newObj.myFunc()
和 myThing.newObj.mySecondFunc()
。
我试着把它改成这样:
for (var k in source) {
if (source.hasOwnProperty(k)) {
if (mtUtils.hasOwnProperty(k)) {
for (var t in k) {
mtUtils[k][t] = source[k][t];
}
} else {
mtUtils[k] = source[k];
}
}
}
但这似乎不起作用。
最佳答案
function extend(dest, source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
var value = source[k];
if (dest.hasOwnProperty(k) && typeof dest[k] === "object" && typeof value === "object") {
extend(dest[k], value);
} else {
dest[k] = value;
}
}
}
return dest;
}
var myThing = {};
extend(myThing, {
newObj: {
myFunc: function() {
console.log('things');
}
}
});
extend(myThing, {
newObj: {
mySecondFunc: function() {
console.log('things');
}
}
});
myThing;
/*
Object
newObj: Object
myFunc: function () { console.log('things'); }
mySecondFunc: function () { console.log('things'); }
__proto__: Object
__proto__: Object
*/
关于Javascript,简单的扩展方法,允许扩展对象的多个版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13709372/