Вопрос

I found this example in a book:

// Create _callbacks object, unless it already exists
var calls = this._callbacks || (this._callbacks = {});

I simplified it so that I did not have to use a special object scope:

var a = b || (b = "Hello!");

When b is defined, it works. When b is not defined, it does not work and throws a ReferenceError.

ReferenceError: b is not defined

Did I do anything wrong? Thank you!

Это было полезно?

Решение

When performing a property lookup like this._callback, if the _callbacks property does not exist for this you will get undefined. However if you just do a lookup on a bare name like b, you will get a reference error if b does not exist.

One option here is to use a ternary with the typeof operator, which will return "undefined" if the operand is a variable that has not been defined. For example:

var a = typeof b !== "undefined" ? b : (b = "Hello!");

Другие советы

It should work in this form:

var b, a = b || (b = "Hello!", b);
//  ^ assign b
//                           ^ () and , for continuation
//                             ^ return the new value of b
//=>  result: a === b = "Hello!"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top