在 Javascript 函数中混合反对表示法和常规样式?
对于精通 javascript 程序员的一个小问题:在 javascript 中声明函数有两种方法。
A: javascript-object-notation
function MyLittleHouseA(name) {
this.age = 88,
this.name = name,
this.getName = function()
{
return this.name;
}
}
B: 嗯,正常:
function MyLittleHouseB(name) {
this.age = 88;
this.name = name;
//do some more proceduaral stuff upon 'construction'
this.age = this.age + 20;
this.getName = function()
{
return this.name;
}
}
我发现 A 更优雅(并且有许多我想变成可配置选项的对象......) ,但可能想在实例创建时做更多的事情,因此我确实需要如 B 所示。
这些可以混合吗?
¡ 谢谢!
A small question for versed javascript programmers: There are two ways to declare a function in javascript.
A: javascript-object-notation
function MyLittleHouseA(name) {
this.age = 88,
this.name = name,
this.getName = function()
{
return this.name;
}
}
B: uhm, normal:
function MyLittleHouseB(name) {
this.age = 88;
this.name = name;
//do some more proceduaral stuff upon 'construction'
this.age = this.age + 20;
this.getName = function()
{
return this.name;
}
}
I find A more elegant (and have a number of objects I want to turn into configurable options...), but might want to do some more stuff upon instance creation, hence I do need as shown in B.
Can these be mixed?
¡ Thanx !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个选项不使用对象表示法。如果您想使用对象表示法,您可以编写如下内容:
这具有不使用
this
的优点,这意味着您可以避免与this
绑定相关的任何问题。它还隐藏了age
和name
,这可能是理想的,也可能不是——就目前而言,没有办法访问age
,而name
是不可变的,因为它只能通过getName
读取。如果您想将age
公开为普通字段:Your first option doesn't use object notation. If you want to use object notation, you could write something like this:
This has the advantage of not using
this
, which means you avoid any issues with the binding ofthis
. It also hidesage
andname
, which may or may not be desirable -- as it stands, there's no way forage
to be accessed, whilename
is immutable since it can only be read viagetName
. If you want to exposeage
as a normal field: