Skip to content

Instantly share code, notes, and snippets.

View oahehc's full-sized avatar

Andrew oahehc

View GitHub Profile
@oahehc
oahehc / this.js
Last active July 22, 2018 14:22
javascript: this
var func = {
f1: function() {
console.log('f1', this);
var sub = function () {
console.log('sub', this);
};
sub();
},
f2: () => {
console.log('f2', this);
@oahehc
oahehc / closure.js
Created July 23, 2018 00:48
js closure
function f(a) {
return function(b) {
console.log(a, b);
}
}
var func = f('123');
func('321'); // 123 321
const a = () => (
new Promise((res) => {
console.log('-- a start');
setTimeout(() => {
console.log('a');
res('-- a finish');
}, 1000)
})
)
const b = () => (
var now = new Date(); // Date object
now.toDateString() // "Sun Jul 17 2016"
now.toLocaleDateString() // "2016/7/17"
now.toGMTString() // "Sun, 17 Jul 2016 03:16:49 GMT"
now.toISOString() // "2016-07-17T03:16:49.141Z"
now.toUTCString() // "Sun, 17 Jul 2016 03:16:49 GMT"
now.toLocaleTimeString() // "上午11:16:49"
now.toLocaleString() // "2016/7/17 上午11:16:49"
now.toString() // "Sun Jul 17 2016 11:16:49 GMT+0800 (台北標準時間)"
now.toTimeString() // "11:16:49 GMT+0800 (台北標準時間)"
@oahehc
oahehc / closure.js
Created January 1, 2020 01:48
simple example for Javascript closure
function counter() {
let count = 1;
return function getCount() {
count++;
return count;
}
}
const getCountA = counter();
navigator.serviceWorker
.register("/sw.js")
.then((reg) => {
// no controller exist, page wasn't loaded via a service worker
if (!navigator.serviceWorker.controller) {
return;
}
if (reg.waiting) {
// If we have a new version of the service worker is waiting,
const urlsToCache = ["/faq", "/contact"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener("fetch", (event) => {
// hijacking path and return a mock HTML content
if (event.request.url.includes("/faq")) {
event.respondWith(
new Response("<div>Mock FAQ Page</div>", {
headers: { "Content-Type": "text/html" },
})
);
}
// hijacking API request and return mock response in JSON format
// send message to service worker
function handleClickEven() {
worker.postMessage({ action: "skipWaiting" });
}
// receive message
self.addEventListener("message", (event) => {
if (event.data.action === "skipWaiting") {
// skip waiting to apply the new version of service worker
self.skipWaiting();
self.addEventListener("updatefound", () => {
if (reg.installing) {
reg.installing.addEventListener("statechange", () => {
if (worker.state == "installed") {
// display a message to tell our users that
// there's a new service worker is installed
}
});
}
});