茉莉花:这个范围

jasmine: scope of this

来自 jasmine 文档 (http://jasmine.github.io/2.0/introduction.html):

The this keyword

Another way to share variables between a beforeEach, it, and afterEach is through the this keyword. Each spec’s beforeEach/it/afterEach has the this as the > same empty object that is set back to empty for the next spec’s beforeEach/it/afterEach.

我在 Javascript 中对此的理解是,这受限于实际功能的范围。所以我希望它会绑定到 beforeEach/it/afterEach.

内的不同上下文(取决于函数的上下文)

例如

describe('Spec', function (){
  var eachThis = null;
  beforeEach(function(){
    eachThis = this;
  });
  it('check this', function(){
    except(this).toEqual(eachThis);
  }
};

所以这个测试应该通过了。

茉莉花改变了这个行为还是我弄错了什么?

So this test should pass.

是的,确实如此。

Did jasmine change the behavior of this

看起来不像。

did i get something wrong

您的代码中存在语法错误和拼写错误(例如 except -> expect)。


此外,toEqual 不测试对象的身份,因此即使 expect(this).toEqual({}); 也会通过。 toBe 是一个更好的方法。

我认为您的示例可能存在一些问题,但您认为 jasmine 在使用 beforeEachbeforeAll 等时操纵 this 引用是正确的

这是一个说明性示例 -- 请注意,下面列出的所有预期都将通过:

(function() {
  describe("without beforeEach", function () {
    (function() {
      // this is not inside of a beforeEach call
      this.dog = "Spot";
      alert(this.dog);
    })();
    it("should not have access to a dog property from `this`", function () {
        expect(this.dog).toBeUndefined(); // because there is no `dog` member of the object currently referenced by `this`
    });
  });

  describe("a beforeEach test", function () { 
    beforeEach(function () {
        this.dog = "Spot";
    });
    it("should work now because we used `beforeEach`", function () { 
        expect(this.dog).toEqual("Spot");
    });

  });
})();

一般来说,您认为 'this' 在函数范围内定义是正确的,但是 jasmine 中的这个实现演示了如何提供一个特定对象以供 'this' 关键字引用如果你想。在 javascript 中完成此操作的典型方法是使用 Function.prototype.apply(),它允许您为 this 引用传入任意对象作为函数的第一个参数。