凌优教育
您的当前位置:首页JavaScript使用prototype定义对象类型(转)[_javascript技巧

JavaScript使用prototype定义对象类型(转)[_javascript技巧

来源:凌优教育


From: JavaEye.com

prototype提供了一套JavaScript面向对象基础设施,我们可以使用它来进行面向对象编程,定义对象类型方式如下: var Person = Class.create();
Person.prototype = {
initialize : function(name, age) {
this.name = name;
this.age = age;
},
toString : function() {
document.writeln("[name]:"+this.name+"
"+"[age]:"+this.age);
}
}
先使用Class.create()来创建一个对象类型,然后定义该对象类型,注意initialize方法是Person的构造器,完整的HTML如下:


Test Object



var Person = Class.create();
Person.prototype = {
initialize : function(name, age) {
this.name = name;
this.age = age;
},
toString : function() {
document.writeln("[name]:"+this.name+"
"+"[age]:"+this.age);
}
}

var person = new Person("robbin",30);
person.toString();


显示全文