前端的第十六天(JavaScript作用域、预解析、对象)
一、作用域
1.作用域
<script>
var num = 321;
if(true){
var num = 123;
console.log(num);
}
console.log(num); //输出为123
</script>
2.变量的作用域
3.作用域链
答案是输出123
答案是a为4 , b为‘22’
二、预解析
1.预解析
报错
undefined
undefined
报错
2.变量预解析和函数预解析
function a() { return false; } ; 1
3.预解析案例
undefined
undefined ; 20
undefined ; 9
9 ; 9 ;9 ; 9 ; 9 ; 报错
三、对象
1.对象
2.创建对象的三种方式
<script>
var obj = {
name : '可可',
type : '阿拉斯加犬',
age : 5,
color : '棕红色',
bark : function(){
alert('汪汪汪');
},
showFile : function(){
alert('演电影');
}
}
console.log(obj.age);
console.log(obj['type']);
console.log(obj.bark());
console.log(obj.showFile());
</script>
</body>
<script>
var obj = new Object();
obj.name = '鸣人';
obj.sex = '男';
obj.age = 19;
obj.skill = function(){
alert('影分身');
}
console.log(obj.name);
console.log(obj.sex);
console.log(obj.age);
console.log(obj.skill());
</script>
<script>
function Hero(name,type,blood){
this.name = name;
this.type = type;
this.blood = blood;
this.attack = function(attack) {
console.log(attack);
}
}
var houyi = new Hero('后羿','射手','3200');
var lianpo = new Hero('廉颇','坦克','5600');
lianpo.attack('远程');
console.log(houyi.blood);
console.log(houyi.name);
console.log(houyi.type);
console.log(lianpo.blood);
console.log(lianpo.name);
console.log(lianpo.type);
houyi.attack('近程');
</script>
3.new关键字
4.遍历对象属性
5.小结以及作业
<script>
function Computer(color,height,brand){
this.color = color;
this.height = height;
this.brand = brand;
this.skill = function(skill){
console.log(skill);
}
}
var computer = new Computer('white','2kg','asus');
computer.skill = ('敲代码');
for(k in computer){
console.log(computer[k]);
}
</script>