JavaScript中创建对象的方法有三种:
使用new 关键字调用构造器创建对象:适用new关键字调用构造器创建对象,这是最津津面向对象语言 创建对象的方式,new关键字后紧跟函数的方式非常类似于java中new后紧跟构造器的方式,通过这种方式创i结案对象简单直观。
看如下代码:
function Person (name,age){
this.name=name;
this.age= age;
}
var p1 = new Person();
var p2 = new Person('yeeku',18);
上面代码一两种方式创建了Person对象。
使用Object直接创建对象:JavaScript的对象都是Object类的子类,因此可以用如下方法创建对象。
//创建一个对象
var myObj = new Object();
使用json语法创建对象:JSON语法提供了一种跟简单的方式来创建对象,使用json语法可避免书写函数,也可以避免适用new关键字,可以直接创建一个JavaScript对象。从js1.2开始,创建对象有了一中更加快捷的语法,语法如下
var p = {
name :'yeeku',
gender:'male';
};
alert(p);
创建类以及继承类
构造器实现伪继承:
function Person (name,age){
this.name = name;
this.age = age;
this.sayHello = function(){
console.log(this.name+"say hello to yuo");
}
}
var per = new Person('yeeku',22);
per.sayHello();
function Student(name ,age,grade){
this.inherit_temp = person;
this.inherit_temp(name,age);
this.grade = grade;
}
Student.prototype.intro = function(){
console.log("%s是个学生,读%d年级",this.name,this.grade);
}var stu = new Student ('leo',34,5);
stu.sayHello();
stu.intro();
其中 **this.inherit_temp = person;this.inherit_temp(name,age);**便是构造器实现伪继承的语句。
使用apply或者call实现伪继承:
function Person (name,age){
this.name = name;
this.age = age;
this.sayHello = function(){
console.log(this.name+"say hello to yuo");
}
}
var per = new Person('yeeku',22);
per.sayHello();
function Student(name ,age,grade){
//Person.call(this,name,age);
Person.apply(this[name,age]);
this.grade = grade;
}
Student.prototype.intro = function(){
console.log("%s是个学生,读%d年级",this.name,this.grade);
}var stu = new Student ('leo',34,5);
stu.sayHello();
stu.intro();
apply和call实现伪继承的语句是:
//Person.call(this,name,age);
Person.apply(this[name,age]);
请看如下例题:
1、定义一个动物类包括年龄、性别,并做出展示。
2、定义一个狗类继承动物类的年龄、性别,添加种类、姓名,狗吠属性,并做展示。
3、定义一个猫类继承狗类的属性,并做出展示。
代码如下:
function anim(age,sex){
this.age = age;
this.sex = sex;
}
anim.prototype.info = function(){
document.writeln('age:'+this.age+'sex:'+this.sex);
}
function dog(name,age,sex,bark,type){
anim.call(this,age,sex);
this.name = name;
this.bark = bark;
this.type = type;
}
dog.prototype.info = function(){
document.writeln("name:"+this.name+'age:'+this.age+'sex:'+this.sex+'bark:'+this.bark+'type:'+this.type+'<br />');
}
function cat(name,age,sex,bark,type){
dog.call(this,name,age,sex,bark,type);
}
cat.prototype.info= function(){
document.writeln("name:"+this.name+'age:'+this.age+'sex:'+this.sex+'bark:'+this.bark+'type:'+this.type+'<br />');
}
var erha = new dog('二哈',3,'公','汪汪汪汪汪','哈士奇');
erha.info();
var bosi = new cat ('咪咪',2,'母','喵喵喵','波斯猫');
bosi.info();
其中的继承是通过调用call()方法实现的伪继承。也可以换为apply()方法。