Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
子函数中的Javascript新关键字_Javascript - Fatal编程技术网

子函数中的Javascript新关键字

子函数中的Javascript新关键字,javascript,Javascript,我试图整理一下“new”关键字在Javascript中是如何工作的。但它有一个奇怪的行为。当我在节点中运行此代码时: var testing = function() { self = this; this.abc = 'abc'; console.log(this); // ====> 1 var subMethod = function () { console.log(this); // =====> 2 console.log(self =

我试图整理一下“new”关键字在Javascript中是如何工作的。但它有一个奇怪的行为。
当我在节点中运行此代码时:

var testing = function() {
  self = this;
  this.abc = 'abc';
  console.log(this); // ====> 1

  var subMethod = function () {
    console.log(this);  // =====> 2
    console.log(self === this); // ====> 3
  };
  //subMethod.apply(this);
  subMethod();
};


test = new testing();
// test = testing(); // ===> *4
log(self==this)给了我false。 nr1中的'this'是{abc:'abc'},子方法中的'this'是全局'this'对象。有人能给我解释一下这种行为吗?
如果我使用subMethod.apply(this)运行,那么console.log(self==this)为true({abc:'abc'})

当我在没有new关键字(*4)的情况下运行时,“this”变量与全局“this”变量相同(如预期),并且console.log(self==this)也是true。


为什么子方法中的“this”与使用“new”关键字运行时的全局“this”相同。

调用
new testing()
时,函数
testing
将其上下文(
this
)作为新对象运行。第一个日志将是该对象。在内部,当您运行
subMethod()
时,它将在全局上下文中运行。JS就是这样做的。因此,
窗口
,并且
自身!==这是
。如果您使用
this
上下文(
subMethod.apply(this)
)调用它,那么自然地
self==this

当您调用
testing()
时,它将在全局上下文中运行。当您添加
abc
时,它现在是全局的,因为
窗口
。当您调用
subMethod()
时,默认情况下也会在全局上下文中调用它,因此
self===this

所以基本上,运行普通函数是在全局上下文中进行的。将函数作为构造函数运行(使用
new
)会创建新的上下文。运行一个方法(例如
“abaca”。在基本对象的上下文中调用split('a')
)-
split
“abaca”
作为其
this
调用


这有帮助吗?

应用此方法时。subMethod=函数。然后这个范围就像我所期望的{abc:'abc',subMethod:[Function]}相关:它没有明确地讨论
new
,但它确实没有什么特别之处——它完全按照您的期望工作;关闭是棘手的一点