1

我试图理解 JS 的细节,并看到许多对象字面量的例子被传递到构造函数中。这种方法有什么好处,我将如何创建我的对象来使用这种方法?

例如:

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

假设我正在创建一个简单的类。许多简单的 OO 教程建议类似

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

相对于

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

如何创建 Cat 对象以使用这种方法?

4

2 回答 2

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

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

好处是你得到了命名参数(如果你收到很多,你不需要记住顺序)。

对我来说也更具可读性

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

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

此外,提供默认值更容易,例如使用underscore.js

function Cat(params) {

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

  params = _.extend(params, defaults);

}
于 2011-06-22T22:19:17.463 回答
0

在您使用 YUI 的第一个示例中,对象文字仅用作选项字典。它在没有命名参数并且函数需要许多参数的语言中很有用。此外,在 JavaScript 中以这种方式使用默认值更容易。

举个例子:

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({});

这种方法是出于实际目的。

于 2011-06-22T22:25:48.687 回答