2010-11-11 73 views
4

我有以下代码:的JavaScript扩展对象的问题

this.myObject = { 
    key1: "val1", 
    key2: "val2" 
} 

this.aMethod = function (newObject) { 
    ... 

在这里,我希望有一个新的对象(可能是从this.myObject继承),它包含在this.myObject无论是在newObject也一切,领域newObject应覆盖已存在的字段this.myObject

我该如何做?

这个想法是,this.myObject提供了一些默认值 - 但方法的用户可以覆盖这些值。我也接受批评这种总体“模式”的观点。谢谢。

+0

在未来,而不是问你的问题在“代码评论“,在问题文本中提问 - 人们可以将问题看作仅包含文本,并将其视为”不是真正的问题“。 – Oded 2010-11-11 13:14:12

+0

修复它为雅! – 2010-11-11 13:20:02

+0

这是全局代码还是功能代码? – 2010-11-11 13:22:44

回答

5
SomeObject.prototype.someMethod = function() { 

    this.myObject = { key1: 1, key2: 2 }; 

    this.aMethod = function (o) { 
     var newObject = object(this.myObject); 

     for (var prop in o) { 
      if (o.hasOwnProperty(prop)) { 
       newObject[prop] = o[prop]; 
      } 
     } 

     // Now newObject contains all properties from the passed in object 
     // and also inherits all properties from myObject 

    }; 

}; 

注意:我使用@ Marco的答案中的对象函数。

+0

Thanks - Ill接受你在这方面与我一起工作的答案。这比单纯使用JQuery扩展函数更受欢迎吗? – bba 2010-11-11 14:29:04

+1

@bba我还没有看过那个特定的jQuery函数,但总的来说,我总是比我自己的代码更喜欢jQuery,因为jQuery已经过全面测试并且跨浏览器。 – 2010-11-11 14:37:56

0

本应该做的工作:

this.aMethod = function(newObject){ 
    combinedObject = {}; 
    for(key in this.myObject){ 
    combinedObject[key] = this.myObject[key]; 
    } 
    for(key in newObject){ 
    combinedObject[key] = newObject[key]; 
    } 
    return combinedObject; 
} 

或者,如果你使用jQuery,在一条线:

return $.extend({},this.myObject,newObject); 
+0

由于OP的代码是功能代码,因此aMethod函数内部的这个值和它外部的这个值并不是指同一个东西,ergo,this.myObject不会给你代码中早先定义的对象。 – 2010-11-11 13:40:06

+0

Sime - 我需要做些什么:var self = this,在aMethod之外,然后使用self.myObject? – bba 2010-11-11 13:44:41

+0

@bba这样做。但是,这个约定是var that = this;然后that.myObject。 – 2010-11-11 13:53:49

5

因此谈到道格拉斯·克罗克福德:

function object (o) { 
    function F() {} 
    F.prototype = o; 
    return new F(); 
} 

有字面上有几十种方式来做到这一点。 Yahoo Theater的视频和Javascript: The Good PartsObject Oriented Javascript的书籍探索了一些权衡。许多JavaScript库实现了一个简单的“类似”的继承模式,但它只是整个蛋糕中的一小部分。

0

如果这是你要找的东西:

var Base = function() { 
    this.foo = "bar"; 
}; 

var MyClass = new Class({ extends: Base }, function() { 

    this.myMethod = function() { 
     return this.foo; // bar 
    } 

}); 

检查了这一点:精缩2KB简约库,就可以使用,https://github.com/haroldiedema/joii/