A:javascript对象表示法
function MyLittleHouseA(name) { this.age = 88, this.name = name, this.getName = function() { return this.name; } }
嗯,正常:
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; } }
我发现一个更优雅的(并且有许多对象我想变成可配置的选项…),但是可能想在创建实例时做更多的事情,因此我确实需要如B所示。
这些可以混合吗?
唐克斯!
第一个选项不使用对象表示法。如果您想使用对象表示法,可以这样写:
function MyLittleHouse(name) { var age = 88; age += 20; return { getName: function() { return name; } } }
这样做的好处是不使用 this ,这意味着您可以避免 这 . 它也隐藏了 age 和 name ,这可能是可取的,也可能是不可取的——就目前的情况来看,没有办法 年龄 名称 getName 年龄 作为标准字段:
this
这
age
name
年龄
名称
getName
function MyLittleHouse(name) { var age = 88; age += 20; return { age: age, getName: function() { return name; } } }