Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

JavaScript - Function

Back


Function

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
function toCelsius(fahrenheit) {
  return (5 / 9) * (fahrenheit - 32);
}

console.log(toCelsius); //[Function: toCelsius]
console.log(toCelsius(77)); //25
console.log(toCelsius()); //NaN

Argument and Function Scope

console.log(
  "\n-------- function scope/argument: literal value argument --------\n"
);
var x = "5";
var y = "5";

function test(x) {
  x = 10; //先在local寻找, 找到参数
  y = 10; //local没有y, 所以引用global, 即改变y的值, 也影响到函数体外.
}

test(); //该处相对于声明了local变量x, 但没有赋值; 但在函数中赋值为5.
console.log(x, y); //5 10, global x 没有引用; y被引用并改变,所以是10

test(x); //该处将global x的值复制到local x.
console.log(x, y); // 5 10, 方法体中对local x的改变只作用于方法体中, 不影响global x.

console.log(
  "\n-------- function scope/argument: reference type argument --------\n"
);

var obj = {};
function testObj(obj) {
  console.log(obj);
  if (typeof obj === "object") {
    obj["name"] = "a";
  }
}

testObj(); //该处形参obj被声明, 但没有赋值, 所以是undefined
console.log(obj); // {}, 形参obj是local变量, 只在方法体中有效,不影响global obj

testObj(obj); // 因为obj是对象, 是reference type; 该处将global obj的地址复制到形参obj
console.log(obj); // { name: 'a' }, 由于方法体引用global obj 的地址并进行修改, 其效果影响global obj

var obj = {};
function testObjLocal(obj) {
  obj = { a: 9 };
}
testObjLocal(obj);
console.log(obj); //{}, 该处形参obj引用global obj, 但方法体实际上将形参的obj引用为新的对象, 不再是global obj. 而且形参的作用域在方法体内. 所以global obj没有影响.

Arrow Function

// arrow function with body and return
const funName = (paraList) => {
  // function body
  return returnVal;
};

// arrow function that only returns value
const funName = () => returnVal; //without parameters
const funName = (paraList) => returnVal; //with parameters

// call arrow function
funName();


// High-Order Function: Function that excepts other functions as arguments
const funName = (paraFun) = {
  paraFun();
  return returnVale;
}

const argFun = (para)={
  // function body
  return returnVal;
}

// call high-order function with named function
funName(argFun);

// call high-order function with anonymous function
funName(()=>{
  // anonymous function body
})

const obj = {
  name: "John",
  call: () => {
    console.log(this); //{}
    return this.name;
  },
  yell: function () {
    console.log(this); //{ name: 'John', call: [Function: call], yell: [Function: yell] }
    return this.name;
  },
};

console.log(obj.call()); //undefined
console.log(obj.yell()); //John

TOP