javascript对象的几种方式

来源:互联网 发布:淘宝店铺分店 编辑:程序博客网 时间:2024/06/05 21:58

一)基于已有对象扩充其属性和方法

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();


原创粉丝点击