2021年4月13日 星期二
arguments、callee、caller是什麼?
function child() { console.log('(arguments)呼叫child()函式時所傳的參數: %o',arguments); console.log('(arguments.callee)arguments參數本身的函式: %O', arguments.callee); console.log('(arguments.callee.caller)呼叫arguments本身函式child()的函式: %O', arguments.callee.caller); console.log('(child.caller同上)呼叫child()的函式: %O',child.caller); var childSay = `小孩說: 媽~好的,我會乖乖去${[arguments].join('、')}。`; console.log(childSay); } function mother() { var motherSay = `媽媽說: 孩子,媽媽希望你能健康快樂,所以要健康快樂的活著就要定時地: ${[arguments].join('、')}。`; console.log(motherSay); child(arguments); } mother('吃飯','洗澡','睡覺'); /*result:
媽媽說: 孩子,媽媽希望你能健康快樂,所以要健康快樂的活著就要定時地: 吃飯、洗澡、睡覺。
(arguments)呼叫child()函式時所傳的參數: Arguments(3) ["吃飯", "洗澡", "睡覺", callee: ƒ, Symbol(Symbol.iterator): ƒ]
(arguments.callee)arguments參數本身的函式: ƒ child()
(arguments.callee.caller)呼叫arguments本身函式child()的函式: ƒ mother()
(child.caller同上)呼叫child()的函式: ƒ mother()
小孩說: 媽~好的,我會乖乖去吃飯、洗澡、睡覺。 */
PS. console.log 裡變數要以何種方式呈現,可使用字串替換符。
%s => 字串(String)
%d 或 %i => 整數(Integer)
%f => 浮點數(Floating points)
%o => 物件(Object)
%O => JSON
%C => CSS
2021年4月12日 星期一
delete不可刪除的東西
//只要是宣告過後的變數都不能刪除! 如:var、let、const、function,什麼意思呢? 舉例如下:
var thisVar = "I'm Var";
delete thisVar; //return false
let thisLet = "I'm Let";
delete thisLet; //return false
const thisConst = "I'm Const";
delete thisConst; //return false
function thisFunction(){
console.log("I'm Funciton");
}
delete thisFunction; //return false
//但是如果沒有宣告就可以刪除,舉例如下:
thisUndeclaredVar = "I'm UndeclaredVar";
delete thisUndeclaredVar; //return true
thisUndeclaredFunction = function(){
console.log("I'm UndeclaredFunciton");
}
delete thisUndeclaredFunction; //return true
//雖然物件本身不能刪除,但裡頭的屬性(變數)可以刪除,舉例如下:
var obj = {
a: 'a',
b: 'b',
c: 'c'
}
delete obj; //return false
delete obj.a; //return true
//那你妳可能會想問,我到底該如何知道所有的東西哪些能刪哪些不能刪呢?
//來吧,來下一個關鍵Object.getOwnPropertyDescriptor(物件,'屬性');的指令妳就明瞭了!
Object.getOwnPropertyDescriptor(window,'obj');
/* return:
{
configurable: false, //configurable中文翻成"可配置的",所以當true時代表可刪除,false代表不可刪除。
enumerable: true,
value: {a: "a", b: "b", c: "c"},
writable: true
}
*/
Object.getOwnPropertyDescriptor(window.obj,'a');
/* return:
{
configurable: true,
enumerable: true,
value: "a",
writable: true
}
*/
//更好的方法是使用Object.defineProperty來宣告configurable是否可以被刪除。且在嚴格模式(use stirct)下,不宣告的變數會出錯,例如:
'use strict';
thisUndeclaredVar = "I'm UndeclaredVar";
Uncaught ReferenceError: thisUndeclaredVar is not defined
'use strict';
Object.defineProperty(window, 'thisUndeclaredVar', { value: "I'm UndeclaredVar", configurable: true }) delete thisUndeclaredVar; // return true
PS. Object.defineProperty 裡有四種屬性可以設定。
configurable: true or false enumerable: true or false value: Number or "string" or Function or Boolean or Object...etc.
該屬性是否可刪除。true代表可以delete,false則不行。 2.enumerable