2020-07-01 错题总结
1.this的指向问题
var user = {
count: 1,
getCount: function () {
return this.count;
}
};
console.log(user.getCount()); //1
var func = user.getCount;
console.log(func()); // undefined
解析:函数在调用时,this才会发生绑定,谁调用的就指向谁。 console.log(user.getCount()) 是在user作用域中发生的,可以调用到count值;而console.log(func()) 的this指向的是window上下文,这样是不能访问到user的内部变量属性值的。
var color = "green";
var test4399 = {
color: "blue",
getColor: function () {
var color = "red";
alert(this.color);
}
}
var getColor = test4399.getColor;
getColor();
test4399.getColor();
解析:getColor()是在window上下文调用的,this指向window,也就是green; test4399.getColor()的this指向的是test4399作用域,返回 this.color也就是blue。
var myObj = {
foo: "bar",
func: function() {
var self = this;
console.log(this.foo);
console.log(self.foo);
(function() {
console.log(this.foo);
console.log(self.foo);
}());
}
}
myObj.func();
解析:var self = this; this指向myObj,self也指向myObj,得到 bar bar; iife函数的this指向window所以,iife函数内的this.foo 为undefined, self还在指向myObj,所以iife里面的self.foo 为bar
2.作用域共享
var msg = "hello";
for (let i = 0; i < 10; i++) {
var msg = "hello" + i*2 + i;
}
alert(msg); // hello189
解析:这里是for循环,所以for循环内部的msg和外部定义的msg共用同一作用域,是同一变量。如果这里是函数,那就不能共享作用域了。
3.布尔表达式
false == null; // false
null == undefined; // true
NaN == false; // false
NaN == NaN; // false
NaN != NaN; // true
4.返回数组的方法
Object.keys();
String.prototype.split();
Array.prototype.join(); // 将数组转化为字符串。 “,”符号连接原数组的元素
Promise.all(); // 返回的是promise对象
5.typeof
typeof NaN; //number
typeof null; //object
typeof undefined; //undefined
typeof (function () {}()); //undefined
6.forEach()
var arr = [{a:1},{}];
arr.forEach(function(item, idx){
item.b = idx;
});
执行结果是:[{a:1,b:0},{b:1}]
解析:forEach()函数作用于数组的遍历,对数组中的每日一项运行给定函数,回调函数中的item相当于数组的当前项元素,idx相当于当前项元素的索引值。 代码段的实际作用就是:为数组每一项元素添加属性b,b的值为当前项的索引值。
7.触发事件
能够弹出alert信息的:
1. <iframe src = "javascript: alert(1)"></iframe> //页面加载时触发
2. <img src="" onerror = "alert(1)" /> // 当图片不存在,发生错误,触发
3. IE下,<s style = "top:expression(alert(1))"></s> //IE7 下 会连续弹出