'这'在使用之前分配给了一个var

'this' is assigned to a var before being used?

本文关键字:一个 var 分配      更新时间:2023-09-26

我经常看到Javascript代码,其中this被分配给一个变量,用于引用对象的当前实例。

var me = this;
me.someproperty_or_method

他们为什么要这样编码?这是一个更完整的代码片段,

var Preload = function(game){};
Preload.prototype = {
  init: function() {
    var me = this;
    var style = {
      font: "32px Arial",
      fill: "ffffff",
      align: "center"
    };

this.text = this.add.text(me.game.world.centerX, me.game.world.centerY, "Loading: 0%", style);
    this.text.anchor.x = 0.5;
  }
  preload: function(){ 
    this.game.load.text('dictionary', 'assets/dictionary.txt');
  },
  create: function(){
    this.game.state.start("Main");
  }
}

我很确定这不是重复的,其他帖子上给出的答案并不明确。

this与函数的执行上下文有关,该值是在函数执行期间确定的,具体取决于函数的调用方式。

在嵌套函数的情况下,您可能希望访问外部函数的this,而不是内部函数中的this。将其分配给一个变量,内部函数可以访问外部函数的this

function foo(){
  var foosThis = this;
  function bar(){
    var barsThis = this;
    // `this` is bar's `this` which is null.
    // You can't access foo's `this` via `this`
    // But you can access foo's `this` via foosThis
  }
  // Call bar with null as context
  bar.call(null);
}
// Call foo with an object as context
foo.call({});

function.call只是改变函数上下文的多种方式之一。


Q: "在使用之前,‘这个’被分配给了一个var?"


A: this 上下文值始终存在:实际值、当前值和最新值。

您可以从任何您希望的上下文中分配它,并从您所在的任何位置或任何您接触到它句柄的时间存储对它过去值的引用。

事实上:赋值实际上是在读取/执行时发生的,而不是在&而不是在使用之后。

它通常用于保存另一个上下文。如果要将另一个上下文传递到另一个块中,可以使用bind()。示例:

function People() {
    // current `this` is context of `People`
    var I = this;
    var beHappy = function () {
        // current `this` is context of `beHappy`
        var me = this;
        console.log("=== beHappy()");
        console.log("I and me =",    (I === me));    // false
        console.log("this and me =", (this === me)); // true
    };
    var beSad = function () {
        // current `this` is context of `beSad`
        var me = this;
        console.log("=== beSad()");
        console.log("I and me =",    (I === me));    // true
        console.log("this and me =", (this === me)); // true
    }.bind(this);
    var beSleepy = function () {
        console.log("=== beSleepy()");
        console.log("this and I =", (this === I));   // false
    };
    beHappy();
    beSad();
    beSleepy();
}
new People();

正如您在beHappy上看到的,I的值与me不同,因为它包含另一个上下文。但在beSad上,两者持有相同的上下文(这是对People的引用)。