为什么嵌套函数不会成为javascript中外部函数的属性?

问题描述 投票:0回答:1

我的代码如下:

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

javascript javascript-objects prototypejs
1个回答
0
投票

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

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

然后创建一个新对象var newObj = new t();现在从newObj调用函数newObj.bar();这应该工作

© www.soinside.com 2019 - 2024. All rights reserved.