1、关于构造函数
function Fn1(name){
if(name){
this.name = name;
}
}
Fn1.prototype.name = "jack";
let a = new Fn1();
console.log('a:', a.name);
function Fn2(name){
this.name = name;
}
Fn2.prototype.name = "jack";
let b = new Fn2();
console.log('b:', b.name);
a: jack b: undefined
2、关于this指向
对于这个问题,这篇文章写的挺好。
let obj = {
num: 5,
func: function(){
let that = this; // 成员函数中的this是obj
that.num *= 2; // obj.num = 5*2 = 10
(function(){
this.num *= 3; // window.num = 2*3 = 6
that.num *= 4; // obj.num = 10*4 = 40
return function(){ // 仅返回函数,没有执行
this.num *= 5;
that.num *= 6;
}
})()
}
}
var num = 2; // 这个num属于window
obj.func();
console.log(num); // 6
console.log(obj.num); // 40
6 40
总结,匿名函数的this指向window对象;对象中函数的this指向对象本身;var声明的全局变量属于window对象的变量;普通嵌套函数的this始终指向window对象;构造函数中的this指向当前实例;箭头函数的this为外层函数的this。
3、变量提升
if(!('a' in window)){
var a = 1;
}
console.log(a);
undefined
总结,a变量的声明提升,因此a成为window对象的属性,即使这个a=undefined。'a' in window表达式是判断window中是否有a这个属性,这里给a加引号是没错的,不加的话,就会去找a对应的值,即undefined,window中有undefine的属性,同样会返回true。总之,由于a变量提升,所以'a' in window返回true,if语句无法执行,最终打印结果是undefined。
4、CSS样式
<style>
div{
display: flex;
flex-direction: row-reverse;
width: 50px;
height: 50px;
}
span:first-child{
order: 1;
}
span:last-child{
order: 2;
}
</style>
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
3 1 2