1

I have some custom Object definitions like:

var Class1 = function () { this.value = ''; };
var Class2 = function () { this.data = ''; };

Class1.prototype = {
    setObject: function () {
        for (var prop in this){
            if (typeof obj[prop] != 'undefined')
                this[prop] = obj[prop];
        }
    }
}

Class2.prototype = {
    setObject: function () {
        for (var prop in this){
            if (typeof obj[prop] != 'undefined')
                this[prop] = obj[prop];
        }
    }
}

Is there a way to have this method setObject by default to all clases?

Is it better to (simulate) inherit that function from the Object type in JavaScript or is it better to use a global function or to define it one by one?

4
  • What about Class2.prototype = Class1.prototype; ? Commented Aug 15, 2013 at 17:20
  • In your code, what is obj? It looks like you are trying to define default properties for your objects? Commented Aug 15, 2013 at 17:21
  • What are you actually trying to do? Do you want to do "cloning objects"? Objects properties may be structured objects, so you will be working with "references". You should make a special cloning method for each class. Commented Aug 15, 2013 at 17:31
  • @AaronKurtzhals obj is usually a JSON object that would want to have access to the functions defined in the class. @IvanKuckir It works, but is it the best? It is not actually a cloning function it loads data from a plain object. You could clone easily with it... function clone () { var tmp = new Class1(); tmp.setObject(this); return tmp; } Commented Aug 15, 2013 at 17:37

3 Answers 3

2

If you're going to be using a library such as jQuery or underscore, you'll already have access to a resilient extend method (see $.extend, and _.extend), so I would say that there's no reason to reinvent the wheel on these custom object types.

Otherwise, you can have Class1 and Class2 inherit from a common base class:

function BaseClass() {
    ...
}
BaseClass.prototype = {
    setObject: function (obj) {...}
};

function Class1() {
    ...
}
Class1.prototype = new BaseClass();

function Class2() {
    ...
}
Class2.prototype = new BaseClass();

var a = new Class1();
a.setObject({...});

var b = new Class2();
b.setObject({...});

Or, if those objects should not contain a common ancestor, you could define them to use the same setObject function reference:

function setObject(obj) {
    ...
}

function Class1() {
    ...
}
Class1.prototype = {
    setObject: setObject
};
function Class2() {
    ...
}
Class2.prototype = {
    setObject: setObject
}
Sign up to request clarification or add additional context in comments.

7 Comments

It kind of breaks the class definition? or am I using wrongly? http://jsfiddle.net/jaxkodex/C55Lc/
@jaxkodex, your printMe function is buggy (should be str += ..., not str = ...), but either way you shouldn't be rolling your own object inspector. Use console.log and the dev console (typically F12).
@zzzBov why using str = str + is buggy? and I use console.log to check variables, but for the example print it was ok...
@jaxkodex, sorry, i misread it, either way, use the dev console, it'll give you better data. And it appears to be producing the right results.
I don't want to merge objects... I want to set the data from an object, but that is only in the current object.. say an instance A of Class1 wants to take the value from an object { value: '123.01', date: '01/05/09'} I'd call A.setObject({...}) and copy only the ones defined (value not date) thats why I would use for (var prop in this) in the setObject function
|
0

I am not sure if you know that, but there are no classes or methods in Javascript. There are only objects, functions and a special property called "prototype".

The common way of simulating classes is this:

var Class  = function () { this.prop = "hi" };
Class.prototype.doMethod = function () { this.prop = "hi2"; };
Class.prototype.setObject: function () {
    for (var prop in this){
        if (typeof obj[prop] != 'undefined')
            this[prop] = obj[prop];
    }
}

// those classes "inherit" from Class
var Class1 = function () { Class.call(this); this.value = ''; };   
Class1.prototype = new Class();

var Class2 = function () { Class.call(this); this.data  = ''; };
Class2.prototype = new Class();

Comments

0

Ivan showed how to inherit from an object. More information about using constructor functions and inherritance can be found here: Prototypical inheritance - writing up

You can use a mixin pattern as well:

var mixIn=function(target,source){
  for(fn in source){
    if(source.hasOwnProperty(fn)){
      target.prototype[fn]=source[fn];
    }
  }
};
var ObjectSettable = {
    setObject: function () {
        for (var prop in this){
            if (typeof obj[prop] != 'undefined')
                this[prop] = obj[prop];
        }
    }
};
var Class1 = function () { this.value = ''; };
//... Class1.prototype stuff
mixIn(Class1,ObjectSettable);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.