Javascript 面向对象
创建对象的几种方式
1.使用Object或对象字面量创建对象
var student = new Object(); student.name = "abc"; student.age = 20;
2.工厂模式创建对象
function createStudent(name,age){ var student = new Object(); student.name = name; student.age = age; return student; } var student1 = createStudent("aaa",20); var student2 = createStudent("bbb",21);
3.构造函数模式创建对象
function Student(name,age){ this.name = name; this.age = age; this.alertName = function(){ alert(this.name); }; } function Fruit(name,color) { this.name = name; this.color = color; this.alertName = function() { alert(this.name); }; } var v1 = new Student("abc",20); var v2 = new Fruit("apple","red");
4.原型模式创建对象
function Student() { this.name = 'easy'; this.age = 20; } Student.prototype.alertName = function(){ alert(this.name); }; var stu1 = new Student(); var stu2 = new Student(); stu1.alertName(); //easy stu2.alertName(); //easy alert(stu1.alertName == stu2.alertName); //true 二者共享同一函数