From b00ae8db0e7660ec0e80e6df7daa26b48b149846 Mon Sep 17 00:00:00 2001 From: ocean010101 Date: Sat, 23 Mar 2019 15:21:28 +0800 Subject: [PATCH] Complete Signed-off-by: ocean010101 --- test/test.js | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/test/test.js b/test/test.js index 63a72e4..bd36382 100644 --- a/test/test.js +++ b/test/test.js @@ -3,19 +3,19 @@ describe('this', function () { var obj = { say: function () { setTimeout(() => { - // this 是什么?想想为什么? - this.should.equal(null) + // this 是obj,obj.say()通过obj找到say(),所以是在obj环境执行,this 就是obj + this.should.equal(obj) done() }, 0) } } obj.say() - }) + }) it('global', function () { function test() { - // this 是什么?想想为什么? - this.should.equal(null) + // this是global, 因为test()在全局环境执行 + this.should.equal(global) } test() }) @@ -25,10 +25,11 @@ describe('this', function () { var obj = { say: function () { function _say() { - // this 是什么?想想为什么? - this.should.equal(null) + // this 是undefined + //根据函数优先原则:say和_say 函数声明都提升了,然后才提升obj。在say函数中调用obj时,obj还没有初始化 + this.should.equal(undefined) } - return _say.bind(obj) + return _say.bind(obj)//将_say的this绑定到obj }() } obj.say() @@ -38,10 +39,11 @@ describe('this', function () { var obj = {} obj.say = function () { function _say() { - // this 是什么?想想为什么? - this.should.equal(null) + // this 是obj + //_say是函数声明被提升了,say函数表达式没有被提升。这时obj已经被创建并初始化了。将_say的this绑定到obj + this.should.equal(obj) } - return _say.bind(obj) + return _say.bind(obj)//将_say的this绑定到obj }() obj.say() })