内部类对象中的 Javascript 上下文

标签 javascript

在使用 ES6 之前,我们可以像这样实例化一个“类”...

var Animal = function(){}

然后……

var dog = new Animal()

“类”中的上下文将是类(实例)本身

var Animal = function( name ){

   this.name = name;

   this.getName = function(){

      // the context here (this) is the class (Animal)
      return this.name; // works well

   }

}

问题是,如果我不想污染根作用域并使用子对象以用于各种用途,那么上下文将成为保存函数的对象

var Animal = function( name ){

   this.utilities = {

      this.getName : function(){

         // the context here is the 'utilities' object so...
         return this.name // wouldn't work

      }

   }

}

当然我们总是可以使用以下形式的东西

dog.utilities.getName.call(dog)

但这会有点长而且不舒服......

有没有办法创建“实用程序”对象并将上下文应用于其所有函数以指向根范围?不必每次都使用 callapply ? (不使用 ES6 的答案会很棒......)

最佳答案

确保 this 是您希望它在各种 utilities 函数中的样子的一种方法是为它们使用箭头函数,因为箭头函数关闭 this 它们定义的地方:

class Animal {
  constructor(name) {
    this.name = name;
    this.utilities = {
      getName: () => {       // This is an arrow function
        return this.name;    //
      }                      //
    };
  }
}
const dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"

这基本上是旧版 var t = this; 解决方案的 ES2015+ 版本:

function Animal(name) {
  var t = this;
  this.name = name;
  this.utilities = {
    getName() {
      return t.name;
    }
  };
}
var dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"

在这两种情况下,这意味着您正在为 Animal 的每个单独实例创建新的函数对象(代码 将在这些对象之间共享,但是对象是不同的)。这很好,除非会有很多 Animal 实例。

或者,您可以将实例传递给一个助手:

const Animal = (function() {
  class Utilities {
    constructor(animal) {
      this.a = animal;
    }
    getName() {
      return this.a.name;
    }
  }
  
  class Animal {
    constructor(name) {
      this.name = name;
      this.utilities = new Utilities(this);
    }
  }
  return Animal;
})();
const dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"

var Animal = (function() {
  function Utilities(animal) {
    this.a = animal;
  }
  Utilities.prototype.getName = function getName() {
    return this.a.name;
  };
  
  return function Animal(name) {
    this.name = name;
    this.utilities = new Utilities(this);
  }
})();
var dog = new Animal("dog");
console.log(dog.utilities.getName()); // "dog"

...它允许实用程序通过 Utilities.prototype 重用其函数对象。

关于内部类对象中的 Javascript 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530072/

相关文章:

javascript - react : TypeError: Cannot read properties of null (reading 'useContext' ) when trying to use react-bootstrap container

javascript - 在 Drupal 站点的一页上插入 javascript 小部件

javascript - 如何正确拆分React应用程序组件

javascript - 在 onclick 中传递变量 : Uncaught SyntaxError: Unexpected indentifier

javascript - Bootstrap 3 轮播字幕延迟

javascript - 使用 jquery 第二次单击时调用的复选框的单击事件

javascript - 在 ngDialog 中与其他服务一起传递依赖项 - Angular

javascript - 如何从标签获取类名

Javascript 继承 codecademy

javascript - 在客户端安全地执行代码