简体   繁体   中英

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();

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. (Of course, a really good JavaScript engine might realize that and optimize it out. But still...)

  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.

  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 */ } . (Of course, naive lint tools may warn you about that, too.)

#2 goes for the = 0 in var i = 0; as well.

But if you feel strongly about initializing book at the declaration, null would probably be a better choice.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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