Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: setting object properties

I want to be able to do this:

var user1 = {
  name: 'John',
  gender: 'male'
}


var user2 = {
  name: 'James',
  gender: 'male',
  email: '[email protected]'
}

user1.someSetMethod({email: '[email protected]'});
user2.someSetMethod({name: 'Jenny', gender: 'female'});

Desired Outcome:

var user1 = {
  name: 'John',
  gender: 'male',
  email: '[email protected]'
}


var user2 = {
  name: 'Jenny',
  gender: 'female',
  email: '[email protected]'
}

I want a method that will set attributes according to what is passed into the function. Is the attribute doesn't exist I want it to be created, if it does, I want it to be overwritten.

Does a method like this exist in Javascript?

like image 553
wilsonpage Avatar asked Nov 04 '11 12:11

wilsonpage


3 Answers

This is normally called extending your object. Virtually every JavaScript library has its own method to do this. Or you can write your own in a few lines of code.

  • jQuery extend
  • underscore.js extend
  • ExtJS extend
  • MooTools extend
  • Prototype extend

Using jQuery's method, you'd do it like so:

var user1 = {
  name: 'John',
  gender: 'male'
};

$.extend(user1, {
  email: '[email protected]'
});

user1.email === '[email protected]'; //true
like image 110
John Strickler Avatar answered Sep 30 '22 04:09

John Strickler


No, You don't want to do this.

The only way to add a method to all objects is to extend Object.prototype.

Doing so (in ES3 browsers like IE8) has a consequence of adding properties to enumerations.

For example:

Object.prototype.extend = function (o) {
  // clone properties of o into this
};

var someObj = {};
for (var key in someObj) {
  console.log(key); // "extend"
}

The best you can do is use Object.extend

Object.extend(user2, {
  name: "Jenny",
  gender: "female"
});

pd has an implementation of extend or you can use:

Object.extend = function (target, source) {
  for (var key in source) {
    target[key] = source[key];
  }
};
like image 26
Raynos Avatar answered Sep 30 '22 05:09

Raynos


If you are willing to use jquery, you can use it's extend method, along with some defaults that will make sure all of the properties you want are set correctly.

Something like this:

function whatever(obj1) {
    var defaults = {
        name: 'Foo Bar',
        email: '[email protected]',
        gender: 'male'
    };

    return $.extend(defaults, obj1);
}
like image 23
Malevolence Avatar answered Sep 30 '22 04:09

Malevolence