// 创建对象
var obj = {
property:"this is property",
method:function(){
return "I'm a method";
},
// toString会在对象转为字符串的时候被调用,可用作对象本身的描述
toString:function(){
return "I'm a Object";
}
}
// 在JavaScript规范中,任何{}创建的对象都属于Object类,并且允许动态对象;
// 为了让JavaScript具备面向对象的实现机制,有两个不可或缺的元素:constructor function和prototype对象
// 类名首字母大写
function Rectanle(width,height){
// 实例变量前面加this
this.width = width;
this.height = height;
// 定义方法
this.area = function(){
// 获取实例变量一定要加上this
return this.width * this.height;
}
}
// JavaScript中,函数也算是一种对象,有自己的属性和方法;使用Rectanle创建的实例都会三个属性:width,height,area
// JavaScript每个通过构造函数创建的对象都包含一个固定的属性prototype
function Rectanle2(width,height){
this.width = width;
this.height = height;
Rectanle2.prototype.area = function(){
return this.width * this.height;
}
}
var rect = new Rectanle2(10,20);
// 可以在火狐的firebug中输出
console.info("the rectanle area is:"+rect.area());
// 当JavaScript遇到rect.area()时,可以直接在对象上找到area这个属性,并直接调用area()方法,如果创建了100个这样的实例
// 就有100个相同的area在内存里,这显然是不合理的,如果在Rectanle的prototype中定义方法,那么当JavaScript引擎遇到rect.area()时
// 会发现对象里没有这个属性,JavaScript会继续到rect的prototype属性里寻找,rect的prototype是指向Rectanle的prototype,JavaScript
// 引擎在Rectanle.prototype上找到area(),就会调用这个方法,即使100个这样的实例,也没有1个area存在于内存中
// 定义类、类方法与类属性
function Person(){}
Person.id = 0;
Person.createAccount = function(){
Person.id ++;
return new Person();
}
var p1 = Person.createAccount();
var p2 = Person.createAccount();
console.info("the is :"+Person.id);
// JavaScript1.5版本规范中没有抽象类、接口和多重继承,只有单一继承,而继承必须通过prototype来实现
function Person(name,email){
this.name = name;
this.email = email;
}
Person.prototype.getInfo = function(){
return "name:"+this.name+" email:"+this.email;
}
function Employee(name,email,title){
// 如同Java中的super(),必须使用call明确定义scope为Employee的实例
Person.call(this,name,email);
this.title = title;
}
// 如果要继承Person,子类的prototype必须指派为父类的实例
Employee.prototype = new Person();
var employee = new Employee("fuyuwei","fuyuwei@outlook.com","info");
console.info("Employee info is:"+employee.getInfo());
JavaScript的类定义与继承
最新推荐文章于 2023-04-22 15:13:16 发布