Viki

Viki 写东西的地方

努力上进且优秀
x
github
email
bilibili

JavaScript function parameters can actually access each other?

Yes, stop scolding, I am not good, I am overreacting 😩.

const buildFn = (
  name = "Viki",
  sayHi = () => {
    console.log(name);
  }
) => {
  return sayHi;
};

buildFn()(); // is OK, output Viki as expected
buildFn("hi")(); // is OK, output hi as expected
const buildFn2 = (
  obj = { name: "Viki" },
  sayHi = () => {
    console.log(obj.name);
    obj = { name: "VIKI" };
  },
  sayHi2 = () => {
    console.log(obj.name);
  }
) => {
  return { sayHi, sayHi2 };
};

buildFn2().sayHi(); // is OK, output Viki as expected
buildFn2({ name: "hi" }).sayHi2(); // is OK, output hi as expected
const buildFn3 = (
  sayHi = () => {
    console.log(name);
  },
  name = "Viki"
) => {
  return sayHi;
};

buildFn3()(); // isOK, output Viki as well if name is after sayHi
buildFn3(() => console.log(name), "hi")(); // NOTICE: name cannot be accessed by passed sayHi function
const buildFn4 = (
  sayHi = () => {
    console.log(obj.name);
    obj = { name: "VIKI" }; // this will not affect obj in sayHi2
  },
  sayHi2 = () => {
    console.log(obj.name);
  },
  obj = { name: "Viki" }
) => {
  return { sayHi, sayHi2 };
};

buildFn4().sayHi(); // is OK, output Viki as expected
buildFn4().sayHi2(); // NOTICE: still Viki, will not be affected by sayHi

Not only can they access each other, but they are also not affected by the order of the parameters 🙃, you can try it yourself in the console.

Just a note to help me remember.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.