fe-star / exercise4 Goto Github PK
View Code? Open in Web Editor NEW课程练习 4:辨认所有this
课程练习 4:辨认所有this
试了半天全局变量global。。有个地方不太舒服,感觉怪怪的,代码如下:
function test() {
this.ttt = "11";
}
function test2(){
console.log(this.ttt) //11
this.ttt = "22";
}
console.log(global.ttt) //undefined
let ttt = "33";
console.log(global.ttt) //undefined
test();
console.log(global.ttt); //11
test2();
console.log(global.ttt); //22
第一个undefined好理解,第二个,我不是已经赋值了全局变量ttt了么,为何还是输出未定义
全局下的后两个console.log也好理解,但是如果函数内部的这个变量都挂在全局global上了,这不是造成变量污染了么?就像代码中的样子test2中的console.log
求解
问题记录:
(1)
it('bind undefined', function () {
var obj = {
say: function () {
function _say() {
// this 是什么?想想为什么?
this.should.equal(global)
}
return _say.bind(obj)
}()
}
obj.say()
})
在正在定义obj的时候,say就立即执行了,此时的 this
为 global, 此时的obj不存在
当obj.say()执行的时候,obj已经存在了,可是为什么 this
的指向还是 global?
同样的(后者可以理解),
it('bind normal', function () {
var obj = {}
obj.say = function () {
function _say() {
// this 是什么?想想为什么?
this.should.equal(obj)
}
return _say.bind(obj)
}()
obj.say()
})
在给obj赋值的时候,say立即执行了,此时的 this
指向 obj
当obj.say()执行的时候,obj一直存在,this
仍然指向 obj
(2)执行问题
测试用例里面的调用其实不是obj.say()函数,而是obj在定义时执行的函数?
然后obj.say()调用的是下面的紫色的函数吗?
this.should.equal(global)
在终端中断言正常执行,但是尝试使用karma进行测试时,在浏览器中提示global is not defined
。像这种测试用例中出现global的情况该如何使用karma进行测试呢?
老师 为什么43行先报错,第8行后报错
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.