this
在这里指向什么?
const expect = require('chai').expect;
const sinon = require('sinon');
describe('test', () => {
describe('test()', () => {
afterEach(function _test() {
this.xxx = undefined; // What does `this` point here?
});
});
describe('test2()', () => {
afterEach(function _test2() {
this.yyy = undefined; // What does `this` point here?
});
});
});
顺便问一下,如果两个 this
都指向同一个对象,那么在上面的代码中使用 this
是否很好?
更新
代码
describe('test', () => {
console.log(1, this);
before(() => {
console.log(2, this);
});
beforeEach( () => {
console.log(3, this);
});
describe('going deeper', () => {
console.log(4, this);
beforeEach(() => {
console.log(6, this);
});
return it('has increased someVal to 3', function() {
assert.equal(1,1);
//console.log(7, this);
});
});
});
输出:
1 {}
4 {}
test
2 {}
going deeper
3 {}
6 {}
✓ has increased someVal to 3
1 passing (4ms)
代码(将单箭头功能更改为普通功能):
describe('test', () => {
console.log(1, this);
before(() => {
console.log(2, this);
});
beforeEach( () => {
console.log(3, this);
});
describe('going deeper', () => {
console.log(4, this);
beforeEach(function() { // HERE
console.log(6, this);
});
return it('has increased someVal to 3', function() {
assert.equal(1,1);
//console.log(7, this);
});
});
});
输出:
1 {}
4 {}
test
2 {}
going deeper
3 {}
1) "before each" hook for "has increased someVal to 3"
0 passing (6ms)
1 failing
1) test going deeper "before each" hook for "has increased someVal to 3":
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at formatValue (util.js:352:36)
at inspect (util.js:186:10)
at exports.format (util.js:72:24)
at Console.log (console.js:43:37)
at Context.<anonymous> (test3.js:32:15)
最佳答案
在您查询的两个位置中,this
由 Mocha 绑定(bind)到内部 Mocha 对象。例如,该对象允许您做的一件事是更改 Mocha 的配置。就像使用 this.timeout(newValue)
更改异步函数的超时一样。在下面的示例中它并不是特别有用,但 Mocha 可以很好地运行它。例如:
describe('test', () => {
describe('test()', () => {
afterEach(function _test() {
this.timeout(5000);
this.xxx = undefined;
});
it("foo", () => {});
});
describe('test2()', () => {
afterEach(function _test2() {
this.timeout(5000);
this.yyy = undefined;
});
it("foo", () => {});
});
});
请注意,如果您要对 afterEach
回调使用箭头函数,则无法访问 Mocha 为回调设置的 this
值。 (this
将在外部作用域中设置一个值。)
By the way, it is good to use this in the above codes if both this(s) point at the same object?
我不建议在 this
上设置任意字段。无法确定您设置的字段何时会与新版本 Mocha 引入的字段发生冲突。我总是能够在封闭的 describe
中设置一个变量并使用它:
describe('test', () => {
let something;
beforeEach(function _test() {
something = fetchATestFixtureFromSomewhere();
});
it("foo", () => {
// use the variable something here.
});
});
<小时/>
关于您的更新。在控制台上任何地方都会出现 {}
,这是因为包含 console.log
的所有函数都是箭头函数,正如我上面所说,如果您使用箭头函数,则 < em>您无法访问 Mocha 绑定(bind)到 this
的对象,因为在这种情况下,this
是从外部作用域获取的,而不是从绑定(bind)到的值获取的功能。如果所有封闭函数都是箭头函数,则 this
来自最外层作用域,并且在最外层作用域中具有值 {}
。
您收到的错误是因为您不能将 Mocha 分配给 this
的值转储到控制台,因为正如错误消息所示,它是一个带有循环引用的结构。
关于javascript - mocha测试中以下js箭头函数中 `this`指向什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44977264/