您的位置:首页 > Web前端 > JavaScript

javascript对象的几种方式

2012-03-21 09:27 183 查看
一)基于已有对象扩充其属性和方法

var student = new Object();
student.name = "Chris";
student.sayName = function(name) {
this.name = name;
alert(this.name);
};


二)工厂方式

function getInfo() {
alert(this.name + "," + this.age);
}

function CreateObj() {
var obj = new Object();
obj.name = "Chris";
obj.age = 23;
obj.getInfo = getInfo;
return obj;
}

var obj1 = new CreateObj();
var obj2 = new CreateObj();


三)构造函数方式

function Student(name, age) {
this.name = name;
this.age = age;
this.getInfo = function () {
alert(this.name + "," + this.age);
};
}

var stu = new Student("Chris", 23);
stu.getInfo();


四)原型(prototype)方式

function Student() {
}

Student.prototype.name = "Chris";
Student.prototype.age = 23;
Student.prototype.getInfo = function() {
alert(this.name + "," + this.age);
};

var stu1 = new Student();
var stu2 = new Student();
stu1.name = 'Tony';
stu1.getInfo();
stu2.getInfo();


五)原型构造函数混合方式

function Student() {
this.name = new Array();
this.age = 23;
}

Student.prototype.getInfo = function() {
alert(this.name + "," + this.age);
};

var stu1 = new Student();
var stu2 = new Student();
stu1.name.push("Chris");
stu2.name.push("Tony");
stu1.getInfo();
stu2.getInfo();


六)动态原型方式:在构造函数中,通过标质量让所有对象共享一个方法,而每个对象拥有自己的属性

function Student() {
this.name = "Chris";
this.age = 23;

if (typeof Student.flag == "undefined") {
Student.prototype.getInfo = function() {
alert(this.name + "," + this.age);
};
}
Student.flag = true;
}

var stu1 = new Student();
var stu2 = new Student();
stu1.getInfo();
stu2.getInfo();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: