![]() |
圖片來源:Udemy |
之前我們曾談過"this"這個關鍵字(註1:[筆記] 談談JavaScript中的"this"和它的bug),在這堂課中則會談到另一個JavaScript中的關鍵字,稱做"arguments"。
// Outer Environment console.log(this); // function statement function thisInFunctionStatement() { console.log(this); } thisInFunctionStatement(); // function expression const thisInFunctionExpression = function() { console.log(this); } thisInFunctionExpression();
function addNewPropertyInWindowObject() { console.log(this); this.newPropertyInWindow = 'Create a new property.' } addNewPropertyInWindowObject(); console.log(newPropertyInWindow); // Create a new property.
const objectWithThis = { name: 'I am the object', log: function () { console.log(this); } } methodInObject.log();
const objectWithThis = { name: 'I am the object', log: function () { this.name = "Update current object name" // 修改 this.name 的名稱 console.log(this); } } objectWithThis.log();
const objectWithThis = { name: 'I am the object', log: function () { this.name = 'Update current object name' console.log(this); const setNameWithFunction = function(newName) { this.name = newName; } setNameWithFunction('Update object name to "NEW NAME"'); console.log(this); } } objectWithThis.log();
const objectWithThis = { name: 'I am the object', log: function () { this.name = 'Update current object name' console.log(this); const setNameWithFunction = function(newName) { this.name = newName; console.log(this); // 確認 this 指稱的對象 } setNameWithFunction('Update object name to "NEW NAME"'); console.log(this); } } objectWithThis.log();
const objectWithThis = { name: 'I am the object', log: function () { var self = this; // 先透過 self 把原本的 this 存起來 self.name = 'Update current object name' const setNameWithFunction = function(newName) { self.name = newName; console.log(self); } setNameWithFunction('Update object name to "NEW NAME"'); console.log(self); } } objectWithThis.log();
// by value (primitives) var a = 3; var b; b = a; a = 2; console.log("a is " + a); console.log("b is " + b); // by reference (all objects (including functions)) var c = {greeting : 'Hello'}; var d; d = c; console.log(c); console.log(d); c.greeting = "Hola"; console.log(c); console.log(d); // by reference (even as parameters) function changeGreeting(obj){ obj.greeting = 'Hi'; //mutate } changeGreeting(d); console.log(c); console.log(d); var c = {greeting : 'Hello'}; var d; d = c; console.log(c); console.log(d); // equal operator sets up new memory space (new address) c = {greeting: "Hola"}; console.log(c); console.log(d);