Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript extending an object question

Tags:

javascript

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.

like image 823
bba Avatar asked Dec 28 '22 05:12

bba


2 Answers

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.

like image 112
Šime Vidas Avatar answered Dec 31 '22 14:12

Šime Vidas


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.

like image 23
Marco Mariani Avatar answered Dec 31 '22 13:12

Marco Mariani