开发者

Benefits of using object literal notation in an object constructor?

I'm trying to understand the finer points of JS and am seeing many examples of object literals being passed into constructors. What are the benefits of this approach and how would I create my object to use t开发者_StackOverflowhis approach?

For example:

myTooltip = new YAHOO.widget.Tooltip("myTooltip", { 
    context: "myContextEl", 
    text: "You have hovered over myContextEl.",
    showDelay: 500
});

Suppose I was creating a simple class. Many simple OO tutorials suggest something like

myCat = new Cat();
myCat.name = "fluffy";
myCat.friendly = true;
myCat.lives = 9

As opposed to

myCat = new Cat({
    name: "fluffy", 
    friendly:true,
lives: 9
})

How do I create the Cat object to use this approach?


function Cat(params) {
 this.name = params['name'];
 this.friendly = !!params['friendly'];
  //etc
}

var tom = new Cat({'name' : 'tom', 'friendly' : 'true'});

The benefits are that you get named parameters (if you receive a lot of them, you don't need to remember the order).

To me is also more readable

new Cat({'name' : 'tom', 'friendly' : 'true', 'lives' : 9});

Than

new Cat('tom',true,9);

Moreover it's easier to provide defaults, like using underscore.js for example:

function Cat(params) {

  var defaults = {'friendly' : true, 'lives' : 9};

  params = _.extend(params, defaults);

}


In your first example with YUI the object literal is used simply as a dictionary of options. It's useful in a language where there are no named parameters and a function takes many arguments. Also it's easier to play with defaults this way in JavaScript.

Take the following example:

function myf(options) {
  var url = options['url'] || 'http://...';
  var method = options['method'] || 'get';
  // ...
}

// Now you can pass only what you deem necessary in the function
myf({ 'url' : 'http://stackoverflow.com' });
myf({ 'method' : 'post' });
myf({});

This method is there for it's practical purposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜