用于访问变量的 var 关键字作用域和函数名

The var keyword scope and function name used to access variables

如何在函数体外部仍然可以访问 prop1?

function myFunc() {
  var prop1 = 10;
  this.myChildFunc = function() {
    alert("value of prop1: " + prop1);
  }
}

myFunc();
myFunc.prop1 = 20; // How prop1 is still accessible using function name ? and outside function scope?
alert("prop1:" + myFunc.prop1);

函数是对象,所以可以有属性,但这些只是属性,仅此而已。

因此,您在函数 (var prop1) 中声明的 变量 无关 属性 在函数对象上 (myFunc.prop1)。他们只是同名而已。

想看就看这个:

function myFunc() {
  var prop1 = 10;
  console.log(prop1);
}

myFunc();                  //10
console.log(myFunc.prop1); //undefined - no such property
myFunc.prop1=20;           //myFunc.prop1 is now 20
myFunc();                  //variable is still 10
console.log(myFunc.prop1); //property is still 20