简体   繁体   English

在对象构造函数中使用对象文字符号的好处?

[英]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. 我试图了解JS的优点,并看到许多对象文字传递给构造函数的示例。 What are the benefits of this approach and how would I create my object to use this 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 许多简单的OO教程建议类似

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? 如何创建Cat对象以使用此方法?

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: 此外,提供默认值也更容易,例如使用underscore.js

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. 在第一个使用YUI的示例中,对象文字直接用作选项字典。 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. 同样,在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. 出于实际目的使用该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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