精通javascript程序员的一个小问题:有两种方法可以在javascript中声明一个函数。
答: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所示。
这些可以混合使用吗?
¡Thanx!
答案 0 :(得分:3)
您的第一个选项不使用对象表示法。如果你想使用对象表示法,你可以这样写:
function MyLittleHouse(name) {
var age = 88;
age += 20;
return {
getName: function() {
return name;
}
}
}
这样做的好处是不使用this
,这意味着您可以避免this
绑定的任何问题。它还隐藏age
和name
,这可能是也可能不合适 - 因为它代表age
无法访问,而name
是不可变的,因为它只能通过getName
阅读。如果您想将age
公开为普通字段:
function MyLittleHouse(name) {
var age = 88;
age += 20;
return {
age: age,
getName: function() {
return name;
}
}
}