js的面向对象
对象的作用:封装一些数据。(属性+方法)
基于对象的javascript:无法创建自定义的类型,不能很好的支持继承和多态。
// 创建对象
var hero = new Object();
hero.name = "zs";
hero.level = 0;
hero.diamond = 200;
// 方法
hero.moveLeft = function() {
// move left
};
// 定义对象的方法
hero.attack = function(name) {
// 只有在当前hero对象的方法中,this才是当前hero对象。
console.log(this.name + " 攻击 " + name);
};
hero.attack("zyf"); // 调用对象的方法
eg:
function createStudent(name,age ,sex,score) {
var student = new Object();
student.name = "ss";
student.age = 18;
student.sex = 1;
student.score = 100;
student.sayHi = function() {
// this代表当前对象
console.log("大家好,我是" + this.name);
}
return student;
}
var stu1 = createStudent("mh", 19, 1, 99);
var stu2 = createStudent("mh", 10, 0, 90);
stu1.sayHi();
stu2.sayHi();
自定义构造函数,比上面的方法,省了第一句,最后一句代码。
function Student(name, age, sex, score) {
// 对象的属性
this.name = name;
this.age = age;
this.sex = sex;
this.score = score;
// 对象的方法
this.sayHi = function() {
// this代表当前对象
console.log("大家好,我是" + this.name);
}
}
//1 内存开辟空间,存储新创建的对象
//2 把this设置为当前对象
//3 执行函数内部的代码,设置对象的属性和方法
//4 返回新创建的对象
var s1 = new Student("ff", 18, 1, 92);
js中的对象:无序属性的集合。
其属性可以包含基本值,对象或函数。对象就是一组没有顺序的值。我们可以把js中的对象想象成键值对,
其中之可以是数据和函数。