Q1. 元素水平居中的实现方法
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
一. 使用弹性盒模型flex实现
.father {
display: flex;
justify-content: center; // 水平
align-items: center; // 垂直
}
二. 使用定位position
必须知道子元素宽高
.father {
position: relative;
width: 400px;
height: 400px;
}
.son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-top: -100px;
margin-left: -100px;
}
三. 使用position+transform
.father {
position: relative;
width: 400px;
height: 400px;
}
.son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform:translate(-50%, -50%) /*表示子元素分别向左向上移动自身宽度和高度的一半*/
}
四. 使用position + margin: auto
.father {
position: relative;
width: 400px;
height: 400px;
}
.son {
position: absolute;
left: 0;
top:0;
bottom:0;
right: 0;
margin: auto;
}
Q2. 没有高度的inline-block,父元素却有高度,为什么?
子元素设置:dispaly:inline-block
,导致了BFC,撑开了父元素的高度,但由于子元素没有任何内容,那么父元素高度就由浏览器默认样式决定(受font-size/height等影响)
Q3. 类的继承
一. 构造函数继承
子类的构造函数中执行父类的构造函数,并为其绑定子类的this,让父类的构造函数把成员属性和方法都挂载到子类的this上去。
优点:避免多个实例共享一个原型实例;能向父类的构造函数传参。
二. 原型链继承
将子类的原型对象指向父类的原型实例上去。
缺点:
- 所有的子类实例原型都指向同一个父类实例;
- 创建子类实例时无法向父类构造函数传参。
三. 组合式继承
构造函数继承和原型链继承的结合。
缺点:每次创建子类都会执行两次父类的构造函数。
四. 寄生组合式继承
将指向父类的实例改成指向父类的原型。
实现多继承
js循环拷贝继承的多次使用。
// 父类1
function Parent1(name,age){
this.name = name;
this.age = age;
this.height=180;
}
Parent1.prototype.say = function(){
alert('hi...');
}
// 父类2
function Parent2(name,age,weight){
this.name = name;
this.age = age;
this.weight = weight;
this.height = 170;
this.skin='yellow';
}
Parent2.prototype.walk = function(){
alert('walk...');
}
// 实现多继承
function Child(name,age,weight) {
Parent1.call(this, name, age)
Parent2.call(this, name, age, weight)
}
for (var i in Parent1.prototype) {Child.prototype[i] = Parent1.prototype[i]}
for (var i in Parent2.prototype) {Child.prototype[i] = Parent2.prototype[i]}
var c1 = new Child('xiaoming',10,8);
console.log(c1);
Q4. var、let、const
var
声明变量存在变量提升,let
和const
不存在变量提升;let
和const
只在当前块作用域生效,var
不存在块级作用域;const
声明时必须赋值,并且只能进行一次赋值。即声明后不能再修改,如果是复合类型数据,可以修改其属性。- 同一作用域下,
var
可以声明同名变量,let
和const
不可以