上述代码行的目的是什么?通过对函数(){}'进行OR运算,我特别感到困惑。为什么空功能?为了给代码行提供更多的上下文,这里是更完整的函数定义。
this.detectQRCode = function(imageData, callback) {
callback = callback || function() {};
client.decode(imageData, function(result) {
if(result !== undefined) {
self.currentUrl = result;
}
callback(result);
});
};
答案 0 :(得分:0)
这只是一种“短路”编码风格。它正在检查以确保回调未定义。如果它是未定义的,那么它将为它分配一个匿名函数,以使callback()代码不会失败。
相当于
import Queue
from Queue import Empty
import threading
import sys
import time
def get_input():
print("Started the listening thread")
for line in iter(sys.stdin.readline, ''):
print("line arrived to put on the queue\n")
q.put(line)
sys.stdin.close()
print("Hi, I'm here via popen")
q = Queue.Queue()
threading.Thread(name = 'input-getter',
target = get_input).start()
print("stdin listener Thread created and started")
# Read off the queue - note it's being filled asynchronously based on
# When it receives messages. I set the read interval below to 2 seconds
# to illustrate the queue filling and emptying.
while True:
time.sleep(2)
try:
print('Queue size is',q.qsize())
print('input:', q.get_nowait())
except Empty:
print('no input')
print("Past my end of code...")
这种方法的一个缺陷是,如果定义了回调,但不是函数,那么在无法调用的东西上使用D:\>comms_test.py
D:\>echo "In the bat cave (script)"
"In the bat cave (script)"
D:\>python myapp.py
Hi, I'm here via popen
Started the listening threadstdin listener Thread created and started
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 2)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 3)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 4)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
('Queue size is', 5)
('input:', 'my message\n')
line arrived to put on the queue
line arrived to put on the queue
D:\>('Queue size is', 6)
('input:', 'my message\n')
('Queue size is', 5)
('input:', 'my message\n')
('Queue size is', 4)
('input:', 'my message\n')
('Queue size is', 3)
('input:', 'my message\n')
('Queue size is', 2)
('input:', 'my message\n')
('Queue size is', 1)
('input:', 'my message\n')
('Queue size is', 0)
no input
('Queue size is', 0)
no input
('Queue size is', 0)
no input
将导致错误。最好使用
if(typeof(callback) == "undefined") callback = function(){};