再看JavaScript非同步程式設計這本書,然後看到了一段程式碼
var webSocketCache = {};
function openWebSocket(serverAddress, callback) {
var socket;
if (serverAddress in webSocketCache) {
socket = webSocketCache[serverAddress];
if (socket.readyState === WebSocket.OPEN) {
callback();
} else {
socket.onopen = _.compose(callback, socket.onopen);
};
} else {
socket = new WebSocket(serverAddress);
webSocketCache[serverAddress] = socket;
socket.onopen = callback;
};
return socket;
};
書中說
var socket=openWebSocket(url,function(){
socket.send('Hello,server!');
});
這樣會使程式碼崩潰,不解。 。在返回值之前調用回調函數為什麼會使程式碼崩潰。希望大佬們能幫我解釋解釋
漂亮男人2017-05-16 13:44:47
const func = function (callback) {
callback();
return 100;
};
const x = func(() => {
console.log(x); //此处将打印 undefined;
});
console.log(x); //此处打印 100
這樣解釋不知道你能否明白?