对象
JavaScript中没有『类』的概念,对于系统内置的对象可以直接创建使用。
①使用new关键字创建对象
var obj01 = new Object();
obj01.stuName = "tom";
obj01.stuAge = 20;
obj01.stuSubject = "java";
console.log(obj01);
②使用{}创建对象
var obj02 = {
"soldierName":"john",
"soldierAge":35,
"soldierWeapon":"gun"
};
console.log(obj02);
③给对象设置函数属性
var obj01 = new Object();
obj01.stuName = "tom";
obj01.stuAge = 20;
obj01.stuSubject = "java";
obj01.study = function() {
console.log(this.stuName + " is studying");
};
console.log(obj01);
obj01.study();
或:
var obj02 = {
"soldierName":"john",
"soldierAge":35,
"soldierWeapon":"gun",
"soldierShoot":function(){
console.log(this.soldierName + " is using " + this.soldierWeapon);
}
};
console.log(obj02);
obj02.soldierShoot();
④this关键字
- 在函数外面:this关键字指向window对象(代表当前浏览器窗口)
- 在函数里面:this关键字指向调用函数的对象
console.log(this);
function getName() {
console.log(this.name);
}
var obj01 = {
"name":"tom",
"getName":getName
};
var obj02 = {
"name":"jerry",
"getName":getName
};
obj01.getName();
obj02.getName();
5、数组
① 使用new关键字创建数组
var arr01 = new Array();
arr01.push("apple");
arr01.push("orange");
arr01.push("banana");
arr01.push("grape");
for (var i = 0; i < arr01.length; i++) {
console.log(arr01[i]);
}
arr01.reverse();
for (var i = 0; i < arr01.length; i++) {
console.log(arr01[i]);
}
var arrStr = arr01.join(",");
console.log(arrStr);
var arr02 = arrStr.split(",");
for (var i = 0; i < arr02.length; i++) {
console.log(arr02[i]);
}
var ele = arr01.pop();
console.log(ele);
② 使用[]创建数组
var arr03 = ["cat","dog","tiger"];
console.log(arr03);