所以我有这段代码:
describe('main describe', function() {
afterEach(function() {
//this.prop === undefined
});
describe('sub', function() {
it('should do something', function() {
this.prop = 'test';
});
});
});
我不知道为什么 main
afterEach
中的 this.prop
是 undefined
因为下面的代码按预期工作:
describe('main describe', function() {
afterEach(function() {
//this.prop === 'test'
});
it('should do something', function() {
this.prop = 'test';
});
});
为什么第一个代码不能像我想的那样工作,其中 this.prop 应该等于 'test'
而不是 undefined
?
this
关键字是否仅绑定(bind)到它直接包含的 describe
函数?
最佳答案
是的,每个 describe
都有一个新的 Context
对象。 (我提到的所有类都可以在 Mocha 的源代码中找到。)你可以得到你想要做的事情:
describe('main describe', function() {
afterEach(function() {
console.log(this.prop);
});
describe('sub', function() {
it('should do something', function() {
this.test.parent.ctx.prop = 'test';
});
});
});
this.test.parent.ctx.prop
行是关键。 this
是与 it
调用关联的 Context
。 this.test
是与 it
调用关联的 Test
对象。 this.test.parent
是与 describe
调用关联的 Suite
对象,它立即包含 it
调用。 this.test.parent.ctx
是 describe
调用 出现 的有效上下文,恰好与 是同一个上下文this
在 afterEach
调用中。
我实际上建议不要遍历 Mocha 的内部结构,而是做类似的事情:
describe('main describe', function() {
var prop;
afterEach(function() {
console.log(prop);
});
describe('sub', function() {
it('should do something', function() {
prop = 'test';
});
});
});
关于javascript - Mocha 和 this 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27575423/