为什么嵌套函数没有';t成为javascript中外部函数的属性?

为什么嵌套函数没有';t成为javascript中外部函数的属性?,javascript,javascript-objects,prototypejs,Javascript,Javascript Objects,Prototypejs,我有一个代码如下: 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:

我有一个代码如下:

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]
它给出如下输出:

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()的属性?

您使用的是类构造函数,但没有绑定它,当使用构造函数时,使用这个关键字绑定变量,这就是为什么bar不是t()的属性。你喜欢这样吗

function t() {
var name = "abc";
this.bar = function() {
console.log(this);
console.log('bar');
   };
};
然后制作一个新对象 var newObj=newt(); 现在从newObj调用函数 newObj.bar();
这应该可以工作

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

函数范围内的变量(如
bar
)与函数体中定义的任何其他变量相同;它不是函数的属性,在函数执行之前不存在
bar
声明一个全局变量,因此它被绑定到
window.bar
并在函数执行后保持不变。如果它是本地的,则在函数返回时会被销毁

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

函数foo(){
foo.baz=42;
}
foo.bar=43;
foo();
console.log(foo.bar,foo.baz)