tpai
11/22/2015 - 11:14 AM

JS 相關筆記

JS 相關筆記

Closure 閉包函數

By call method which return from function to change local variable.

藉由呼叫函數中回傳的方法變更區域變數。

Ref:

call/apply && bind

被借用的方法.call(目標, ...參數) => 目標.被借用的方法(...參數)

被借用的方法.apply(目標, [...參數]) => 目標.被借用的方法(...參數)

var arr = [];
Array.prototype.push.apply(arr, ["a", "b", "c", "d"]); // arr.push("a", "b", "c", "d")
console.log(arr); // Result: ["a", "b", "c", "d"]

String.prototype.split.call("1,2,3,4", ","); // "1,2,3,4".split(",")
// Result: ["1", "2", "3", "4"]

方法.bind(目標) => 方法可存取目標物件所定義之成員

class C extends React.Component {
    constructor() {
        this.onMouseClick = this.onMouseClick.bind(this);
    }
    onMouseClick() {
        console.log("mouse click")
    }
    render() {
        <div onClick={this.onMouseClick}>TEST</div>
    }
}

Strict Comparison

Difference between '==' and '===':

Former has no type comparison, latter has.

Type

typeof /regexp/ // "object"
typeof [] // "object"
typeof {} // "object"

Variable Hoisting

Based on your knowledge of var hoisting, and write the code below:

a = 1;
var a;

Browsers Brawl

List two or three hack tricks to deal with different browsers:

Selector, property, value, javascript, css and html hacks.

Ref: Browser Hacks

Pseudo What?

What's the difference between pseudo element and class?

  • Pseudo Element: Certain part of content of the element to be selected. (ex. ::first-line)
  • Pseudo Class: Describe a special state of the element to be selected. (ex. :hover)

Module Import

Write down at least two modular javascript style:

RequireJS (AMD)

define(['jquery', 'underscore'], function($, _) {...}

CommonJS

// foobar.js
export default const foo = (str) => console.log(str)
export const bar = "Hello, World!";

// main.js
import foo, { bar } from "foobar";
foo(bar); // "Hello, World!"

Is there something store in my browser?

What's the difference between cookies, localStorage and sessionStorage?

  • cookies: It's attached with http request by default.
  • localStorage: Information store until user delete.
  • sessionStorage: It'll be clear after user close tab/browser or logout.
/* Range of date display by moment. */

// yesterday
startDate.add(-1, "days")
endDate.add(-1, "days")

// today
moment()
moment()

// tomorrow
startDate.add(1, "days")
endDate.add(1, "days")

// previous week
startDate.weekday(-7)
endDate.weekday(-1)

// this week
moment().weekday(0)
moment().weekday(6)

// previous month
startDate.startOf("month").add(-1, "months")
endDate.endOf("month").add(-1, "months")

// this month
moment().startOf("month")
moment().endOf("month")

// display weekday
const weekdays = ["日", "一", "二", "三", "四", "五", "六"]
const weekday = i => `星期${weekdays[i]}`;
weekday(moment(date).format("d")); // ex. 星期日