我的代码如下:
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 = new t();现在从newObj调用函数newObj.bar();这应该工作