I have the following code:
this.myObject = {
   key1: "val1",
   key2: "val2"
}
this.aMethod = function (newObject) {
    ...
Here I want a new object (probably that inherits from this.myObject) that contains everything in this.myObject plus whatever is in newObject also, fields in newObject should override already existing fields in this.myObject
How do I do this?
This idea is that this.myObject provides some default values - but the user of the method can override these values.  I'm open to criticisms of this overall "pattern" as well.  Thanks.
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
    };
};
Note: I am using the object function from @Marco's answer.
Thus spoke Douglas Crockford:
function object (o) {
  function F() {}
  F.prototype = o;
  return new F();
}
There are literally dozens of ways to do that. The videos at Yahoo Theater, and the books Javascript: The Good Parts and Object Oriented Javascript explore some trade-offs. Many javascript libraries implement a simple "class-like" inheritance pattern, but it's just a small piece of the whole cake.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With