对象的组成
属性
方法
事件
函数和方法的区别
函数:直接调用的是函数
方法:通过对象调用的是方法
创建对象的三种方式:
一:直接使用Object
var person = new Object();
person.name = “ysy”;
二:使用构造函数,模拟类的定义
function Person(){
this.name = “ysy”;
}
三:使用对象字面量
var stu = {
name: “ysy”;
};
this关键字
this表示当前对象
函数中的this,表示调用函数的当前对象
构造函数中的this,表示将来new出来的当前对象
事件绑定的匿名回调函数中的this,表示事件源(发生事件的元素)
构造函数
用来创建对象的函数,称为构造函数(构造器)
用来定义构造函数,模拟类的定义
function 构造函数名{
this.属性名 = 属性值;
this.方法名 = function(){方法定义};
}
调用构造函数,创建对象:
var 对象名 = new 构造函数名();
<script>
function Computer() {
this.brand = "";
this.typeName = "";
this.price = 0;
this.work = function () {
console.log("计算机正在工作:" + this.brand + "," + this.typeName + "," + this.price);
};
}
var c1 = new Computer();
c1.brand = "联想";
c1.typeName = "台式机";
c1.price = 4600;
c1.work();
var c2 = new Computer();
c2.brand = "戴尔";
c2.typeName = "笔记本";
c2.price = 6600;
c2.work();
</script>
带参的构造函数
为了便于对象的创建以及初始化,通常会使用参数的构造函数
function 构造函数名(形参1,形参2…){
this.属性名 = 形参1;
this.属性名 = 形参2;
this.方法名 = function(){方法定义};
}
可以在创建对象的同时设置属性值
var 对象名 = new 构造函数名(实参1,实参2…);
<script>
function Student(name, age, sex, score) {
this.name = name;
this.age = age;
this.sex = sex;
this.score = score;
this.show = function () {
console.log(this.name + "," + this.age + "," + this.sex);
};
this.study = function () {
console.log("我是一个学生,考试成绩:" + this.score);
};
this.run = function () {
console.log(this.name + "正在参加南京马拉松!");
};
}
//在创建对象的同时为属性赋值
var stu1 = new Student("柏倩", 18, "女", 98);
stu1.show();
stu1.study();
stu1.run();
var stu2 = new Student("陈浩", 28, "男", 89);
stu2.show();
</script>