简体   繁体   中英

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: 'james@gmail.com'
}

user1.someSetMethod({email: 'john@gmail.com'});
user2.someSetMethod({name: 'Jenny', gender: 'female'});

Desired Outcome:

var user1 = {
  name: 'John',
  gender: 'male',
  email: 'john@gmail.com'
}


var user2 = {
  name: 'Jenny',
  gender: 'female',
  email: 'james@gmail.com'
}

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?

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.

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

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

$.extend(user1, {
  email: 'john@gmail.com'
});

user1.email === 'john@gmail.com'; //true

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];
  }
};

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@example.com',
        gender: 'male'
    };

    return $.extend(defaults, obj1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM