最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - creating a object in javascript that has a 'init' method with optional namevalue pairs - Stack Overflow

programmeradmin3浏览0评论

I've seen many javascript objects that have a 'init' method that you pass in values to in order to setup the object.

How do they internally handle the initializations of their private variables when passed in a array of name/value pairs like:

myObject.init( {prop1: "blah", prop2: "asdf", ..., propn: "n"} );

Specifically, some of these values can be optional, so how would you setup defaults and then override them if the name/value pair was passed in during the init.

I've seen many javascript objects that have a 'init' method that you pass in values to in order to setup the object.

How do they internally handle the initializations of their private variables when passed in a array of name/value pairs like:

myObject.init( {prop1: "blah", prop2: "asdf", ..., propn: "n"} );

Specifically, some of these values can be optional, so how would you setup defaults and then override them if the name/value pair was passed in during the init.

Share Improve this question asked Feb 4, 2009 at 21:32 BlankmanBlankman 267k330 gold badges795 silver badges1.2k bronze badges
Add a comment  | 

6 Answers 6

Reset to default 7
var myObject = {
  init: function(options) {
    this.foo = options.foo || 'some default';
    this.bar = options.requiredArg;

    if (!this.bar) raiseSomeError();
  }
}

This tests ok on FF5, IE8, Chrome 12, Opera v11.5. It doesn't matter what the default values are, they will be overwritten if their key is in the calling list, if not they will be left alone.

var myObject = {
   prop1: 'default1',
   prop2: 'default2',
   prop3: 'default3',
   prop4: 'default4',
   prop5: 'default5',
   prop6: 'default6',
   init: function(options) {
      for(key in options) {
         if(this.hasOwnProperty(key)) {
            this[key] = options[key]
         }
      }
   }
}

myObject.init( {prop1: "blah", prop2: "asdf", prop5: "n"} )

The cleanest way I can think of would be to use a defaults object that contains all of the default properties as follows:

function init( args ) {
    this.value = 'value' in args ? args.value : defaults.value;
}

You could even iterate over the default object using a for loop so that you don't have to keep track of which properties you want the object to contain.

You should use the "in" operator since it is possible to actually set the value of a property to undefined. It is valid to set a property to undefined and in that case it is actually considered set, the only way to ensure that a value was not set is to check that it isn't in the object at all.

Better still, get the init method out of the object so you can use init for other objects.

This tests ok on FF5, IE8, Chrome 12, Opera v11.5. It doesn't matter what the default values are, they will be overwritten if their key is in the calling list, if not they will be left alone.

var myGlobal = {
   init: function(obj, options) {
      for(key in options) {
         if(obj.hasOwnProperty(key)) {
            obj[key] = options[key]
         }
      }
   }
}

var myObject = {
   prop1: 'default1',
   prop2: 'default2',
   prop3: 'default3',
   prop4: 'default4',
   prop5: 'default5',
   prop6: 'default6'
}

myGlobal.init( myObject, {prop1: "blah", prop2: "asdf", prop5: "n"} )

oh lets see

edit: updated, this actually works

 
function myObject(){}

myObject.prototype.init = function (argObj)
{
    if (!argObj)
    {
        argObj = new Object();
    }

    var abc = (argObj['abc'] != undefined) ? argObj['abc'] : "default value 1";
    var defg = (argObj['defg'] != undefined) ? argObj['defg'] : "default value 2";
}

You could use a ternary operator to check whether an element of the initialisation array is set, and use it if it is, or use a default if not. For example, assuming the initialization data is passed as an object called init....

var myObject = {
  init: function(opts) {
     this.foo=(typeof(opts.foo)!="undefined")?opts.foo:'default value';
  }
}

Alternatively, you could just copy init array overriding previously set values

var myObject = {
  init: function(opts) {
      this.foo='default value';

      for (name in opts)
      {
         this[name]=opts[name];
      }
  }

Note that an idiom like

this.foo = opts.foo || 'some default';

Fails if opts.foo is set to a value which evaluates to false, e.g. 0

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论