优良部份1~5
1. 宽鬆型别(loose typing)及 易转型
https://codepen.io/Rouoxo/pen/XWzMgvY
(1) 易转型
console.log(!!0); // false console.log(parseInt("169.99cm")); // 169 console.log(parseFloat("169.99cm")); // 169.99 console.log(String(false)); // "false" console.log(Object(169.99)); // Number {169.99}
(2) 判断Array
// 利用Array.isArray()函式 // 利用instanceof运算子判断是否为Array类别 // 利用Object.prototype.toString()函式判断字串 console.log(Array.isArray([])); // true console.log([] instanceof Array); // true console.log(Object.prototype.toString.call([]) == "[object Array]"); // true 好用 var Vtuber = ["茸茸鼠", "阿骂"]; if (typeof Vtuber === "object" && Vtuber.constructor === Array) { console.log("Vtuber是真正的阵列"); }
2. Object Literals 物件实字
https://codepen.io/Rouoxo/pen/qBVrPaa?editors=0012
function getPlayerObj(name, progress) { return { sayHi() { return `Hi, I am ${name}`; }, }; } console.log(getPlayerObj("OneJar", 23).sayHi()); // "Hi, I am OneJar"
3. Hoisting
https://codepen.io/Rouoxo/pen/jOaBGwR?editors=0011
var、具名函式 可使用Hoisting
let 、const、匿名函式、=>(为匿名函式) 无法使用Hoisting
无法在函式宣告之前就使用
console.log("eee+fff", eee() + fff()); //hoisting function eee(cry = 123) { return cry; } function fff(cry = 456) { return cry; }
4. Closure
https://codepen.io/Rouoxo/pen/oNoZGow?editors=0012
var testModule = (function () { var counter = 0; return { incrementCounter: function () { return counter++; }, // 语法糖 物件 resetCounter() { console.log("counter value prior to reset: " + counter); counter = 0; }, }; })(); //test testModule.incrementCounter(); testModule.incrementCounter(); testModule.incrementCounter(); testModule.resetCounter(); //counter value prior to reset: 3
5. Prototype
prototype 似继承 给拿走的变数使用
let Crash = function () { this.name = "Crash"; this.age = 18; this.secret = { weight: 100, fn: function () { console.log(this); // {weight: 100, fn: ƒ} }, }; }; let myCrash = new Crash();
// 接着针对函式的原型添加属性 Crash.prototype.cat = 3; Crash.prototype.dog = 4; console.log(Crash); // 只有原本的资料 console.log("myCrash", myCrash); // 有新增的 myCrash.secret.fn(); // {weight: 100, fn: ƒ}
不良部分
参阅:
https://www.wfublog.com/2012/12/javascript-awful-parts.html
https://codepen.io/Rouoxo/pen/eYevGPJ?editors=0012
全域变数
分号错误
保留字
typeof
parseInt
+
浮点数
undefined 与 NaN
hasOwnProperty()
eval