为什么人们在JS构造函数中访问字段,但没有设置它们?
我一直在阅读很多看起来像这样的代码:
function Constructor(foo) { this.bar; }
用于定义构造方法。 当然,这个领域读什么都不做。 为什么呢? 在很多情况下,我没有看到文档生成器的注释或标签。
引用的TreeParser
代码完全没有。 我的猜测是,它的目的是1)logging对象的属性,或者2)原始作者正在this.foo
和this.foo = undefined
,认为this.foo
类似于var foo
。 不是这样。
TreeParser与以下内容非常相似:
function MyStuff(someArg) { /** * Very brief someArg documentation here. */ this.someArg; // Do some other stuff... this.someArg = someArg; // <-- This line actually does something useful }
总之,这样写代码没有什么好的理由。 良好的文档很重要,但这不是很好的文档。
这段代码完全没有做任何事情。
foo
和this.foo
这个参数不是一回事。 当你看到this.foo
它引用了Constructor
的foo
属性的new
实例,而参数foo
将一个值传递给new Constructor
实例,如:
function Whatever(foo){ this.foo = foo; } var wht = new Whatever('What are you talking about?'); console.log(wht.foo); wht.foo = 'Something Else.'; console.log(wht.foo); var wh = new Whatever('This in a different instance of the same constructor.'); console.log(wh.foo);