1 创建对象

所有的函数都是函数对象。其typeof 结果为function

function Student(name, id) {
This.name = name;
This.id = id;
}

函数声明时,首先创建一个空对象,之后声明一个construtor属性,其值为此函数。
之后把此对象赋给函数对象的prototype属性。所有通过此函数创建的对象都共用prototype属性指向的对象的属性及方法。

var stu1 = new Student(‘cy’, ‘05130312’);

当调用Student时首先会创建一个空对象即new Object()并赋给stu1变量。 之后会把此对象传递给Student函数中的this。 Student内部可以利用this来给对象添加属性及方法。

Student.prototype.study = function () {
alert(‘studing’);
}

如果把方法的声明放入函数内部,那么每创建一个对象都会生成一个指向方法的属性。而方法本来是可以共用的。没有必要每个对象都有一个,因此使用上述方式声明。

总结:

  1. 属性的声明放入函数内部。
  2. 方法的声明放入函数外部,利用prototype方式声明。

2 对象字面量

Var student = {
Id=”00000”,
//如果符合js变量的命名规则,可以不写引号
//值部分如果是字符串类型,必须加引号
Name=”cy”,
Address={
City:Beijing,
Street:chaoyang
}
}
//对象是引用传递
Var obj = student;
//如果key不符合js变量命名规则,需要此方式访问属性。
document.writeln(obj['id']);
document.writeln(obj.id);
obj.id="00000";
document.writeln(obj.id);
document.writeln(student.id);

obj["id"]="555555";
document.writeln(obj.id);
document.writeln(student.id);

document.writeln(obj.name);

document.writeln(obj.address.city);
document.writeln(obj.address.street);

3 修改对象的属性和方法

Var persion = {
Name:’cy’,
method1:function() {
Alert(“aaa”);
}

delete persion.name; //删除属性
delete persion.method1 //删除方法

persion.name = ‘jz’//修改属性
persion.method1 = function() {
alert(“kkkk”);
} //修改方法

4 继承

function Employee(name, job, phone, email, loginname, loginpass) {
//属性声明全部放入构造函数内部
this.name =name;
this.job = job;
this.phone = phone;
this.email = email;
this.loginname = loginname;
this.loginpass = loginpass;
}
//方法声明利用prototype
Employee.prototype.getContact = function (){
alert("phone:" + this.phone +",email:"+this.email);
}

function CleanMan(name, phone, email, loginname, loginpass, tools) {
//此句实现继承,call方法调用Employee函数,第一个参数为函数中this指向的对象。此处传入this代表通过CleanMan函数创建对象时创建的对象。
Employee.call(this, name, 'cleaning', phone, email, loginname, loginpass);
//属性声明放入构造函数内部
this.tools = tools
}
//使用原型链方式继承Employee的所有方法及常量等。这样不可以,Employee.prototype只有一个,以后对CleanMan.prototype添加方法也会使所有的Employee也拥有此方法。这显然是不对的。
//CleanMan.prototype = Employee.prototype;

//这是正确的方法。Clean.prototype指向一个Employee对象。
CleanMan.prototype = new Employee();

//方法声明利用prototype
CleanMan.prototype.cleaning = function () {
alert("working, tools [" + this.tools + "]");
}

var cleanMan = new CleanMan("cy", "132323", "cysy@163.com", 'cysyz', '111', new Array('tiaosao','cuoban','tuobu'));
cleanMan.cleaning();
//继承得到getContact方法
cleanMan.getContact();

//因为使用原型链,因此可以使用instanceof来判断类型。
alert(cleanMan instanceof CleanMan);
alert(cleanMan instanceof Employee);