From da31767df4cc91003b19713237f04162d836c74e Mon Sep 17 00:00:00 2001 From: jiangmengyi <1260501552@qq.com> Date: Sat, 6 Apr 2019 20:48:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E9=80=9A=E8=BF=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/test.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/test/test.js b/test/test.js index 63a72e4..e2f38b7 100644 --- a/test/test.js +++ b/test/test.js @@ -4,7 +4,8 @@ describe('this', function () { say: function () { setTimeout(() => { // this 是什么?想想为什么? - this.should.equal(null) + // this 是 obj, 箭头函数中的this是在定义函数的时候绑定,而不是在执行函数时绑定 + this.should.equal(obj) done() }, 0) } @@ -15,7 +16,8 @@ describe('this', function () { it('global', function () { function test() { // this 是什么?想想为什么? - this.should.equal(null) + // this使用默认绑定(非严格模式),严格模式是undefined + this.should.equal(global) } test() }) @@ -26,8 +28,13 @@ describe('this', function () { say: function () { function _say() { // this 是什么?想想为什么? - this.should.equal(null) + // 《你不知道的js上》书中 96 页 2.4.1 被忽略的this, + // 如果你把null或者undefined作为this的绑定对象传如call,apply或者bind, + // 这些值在调用时会被忽略,实际使用的是默认绑定规则 + // 显示绑定了obj,但是此时 obj 是 undefined, 所以 this 是 global(非严格模式),严格模式是undefined + this.should.equal(global) } + console.log('obj:', obj) return _say.bind(obj) }() } @@ -39,7 +46,8 @@ describe('this', function () { obj.say = function () { function _say() { // this 是什么?想想为什么? - this.should.equal(null) + // this 是 obj,同上一个,因为此时的obj已存在 + this.should.equal(obj) } return _say.bind(obj) }()