为什么嵌套函数没有变成javascript中外层函数的属性?

Why the nested function doesn't becomes the property of the outer function in javascript?

我有一个代码如下:

function t() {
    var name = "abc";
    bar = function() {
    console.dir(this);
    console.log('bar');
 };
};
t.foo = function() {
    console.dir(this);
    this();
    console.log('bar');
};
console.dir(t);

输出如下:

ƒ t()
foo: ƒ ()
arguments: null
caller: null
length: 0
name: "t"
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: VM2091:1
[[Scopes]]: Scopes[2]

所以我们可以看到,在检查函数 t() 时,我们没有找到函数 "bar",但是函数 "foo" 在函数 t() 中。我的问题是为什么函数 "bar" 不是函数 t() 的 属性,而函数 "foo" 成为函数 t()?

的 属性

您正在使用 class 构造函数但未绑定它,当使用构造函数绑定变量时使用此关键字,这就是为什么 bar 不是 t() 的 属性 的原因。这样做

function t() {
var name = "abc";
this.bar = function() {
console.log(this);
console.log('bar');
   };
};

然后制作一个新对象 var newObj=新 t(); 现在从 newObj 调用函数 newObj.bar(); 这应该有效

您可以向任何 JS 对象添加属性,包括函数。因此,当您将 t 登录到控制台时,t.foo = ... 有效并显示为 属性 也就不足为奇了。 t.foo 指向的值是一个函数这一事实纯属偶然——它也可以是字符串、数字或其他任何东西。

bar这样的函数作用域变量与函数体中定义的任何其他变量相同;它不是函数的 属性 并且在函数执行之前不存在。 bar 声明了一个全局变量,因此它绑定到 window.bar 并在函数执行后持续存在。如果它是本地的,它会在函数 returns.

时被销毁

您可以使用 foo.barfoo 内部对函数对象设置 属性,但我无法想象这会有多大用处。

function foo() {
  foo.baz = 42;
}

foo.bar = 43;
foo();
console.log(foo.bar, foo.baz);

在您的函数中,如果这些函数未绑定到任何对象,this 将是 window。如果要将 this 绑定到一个新对象并使用函数构造函数为其设置属性,请使用 new operator:

创建一个实例

function Foo() {
  this.bar = 42;
  this.quux = function () {};
}

Foo.prototype.baz = 43;
Foo.prototype.corge = function () {};

console.log(new Foo());

这里的区别是 this. 函数是在调用构造函数时创建的,而 Foo.prototype. 变量只定义一次。