在对象构造函数中使用对象文字表示法的好处?
我试图理解 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 对象来使用这种方法?
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 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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好处是您可以获得命名参数(如果您收到很多参数,则无需记住顺序)。
对我来说,它也更具可读性,
而且
更容易提供默认值,例如使用 underscore.js :
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
Than
Moreover it's easier to provide defaults, like using underscore.js for example:
在 YUI 的第一个示例中,对象文字仅用作选项字典。它在没有命名参数并且函数需要多个参数的语言中很有用。此外,在 JavaScript 中以这种方式使用默认值会更容易。
举个例子:
这个方法是出于实用目的而存在的。
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:
This method is there for it's practical purposes.