简体   繁体   English

javascript变量空声明或对象

[英]javascript variable empty declaration or object

I know i'm most probably nitpicking but... i have the following code: 我知道我很可能是挑剔但是...我有以下代码:

var book;
var i=0;

i = 300;    
book = new CBook();
book.Title = "blahblah";
book.Contents = "lalalala";


function CBook() {
    this.Title = "";
    this.Contents = "";
}

now my question is: 现在我的问题是:

would it be better to have 拥有它会更好吗?

var book = {};

instead of 代替

var book;

in the first version typeof(book) returns undefined before the assignment book = new CBook(); 在第一个版本中,typeof(book)在赋值簿之前返回undefined = new CBook();

thanks in advance 提前致谢

would it be better to have 拥有它会更好吗?

 var book = {}; 

No, for a couple of reasons: 不,原因有两个:

  1. You'd be creating an object just to throw it away when you did book = new Book(...) later. 当你稍后使用book = new Book(...)时,你正在创建一个对象,只是为了抛弃它。 (Of course, a really good JavaScript engine might realize that and optimize it out. But still...) (当然,一个非常好的 JavaScript引擎可能会意识到并优化它。但仍然......)

  2. If you use lint tools, you'd be actively preventing them from warning you that you attempt to use book before you (properly) initialize it. 如果您使用lint工具,则会在您(正确)初始化之前主动阻止它们警告您尝试使用book

  3. If for some reason you had logic in your code that needed to check whether you'd assigned a book yet, you'd lose the ability to do that. 如果由于某种原因你的代码中有逻辑需要检查你是否已经分配了一本书,那么你就失去了这样做的能力。 By leaving the variable with its default undefined value, that check can be if (!book) { /* Not assigned yet */ } . 通过将变量保留为其默认的undefined值,该检查可以是if (!book) { /* Not assigned yet */ } (Of course, naive lint tools may warn you about that, too.) (当然,天真的lint工具也可能会警告你。)

#2 goes for the = 0 in var i = 0; #2无二= 0var i = 0; as well. 同样。

But if you feel strongly about initializing book at the declaration, null would probably be a better choice. 但是如果你对在声明中初始化book感到强烈,那么null可能是更好的选择。

A variable should be declared closest to its first use. 变量应声明最接近其首次使用。 So, if I were you, I would change to: 所以,如果我是你,我会改为:

var book = new CBook();

Also, I would pass parameters to CBook and use it as a constructor: 另外,我会将参数传递给CBook并将其用作构造函数:

var book = new CBook("blahblah", "lalalala");

function CBook(title, contents) {
   this.title = title;
   this.contents = contents;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM